Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a driverStores collection where each Store has a Product collection 


{ "_id": ObjectId("61444bad0e945f654c1c4918"), "storeName": "One",
"listProducts": [ { "_id": ObjectId("61444bc70e945f654c1c491f"), "productName": "Water", "productPrice": 10 },
{ "_id": ObjectId("61444c050e945f654c1c4927"), "productName": "Milk", "productPrice": 50 } ] }
{ "_id": ObjectId("61444bba0e945f654c1c491b"), "storeName": "Two",
"listProducts": [ { "_id": ObjectId("61444c110e945f654c1c492a"), "productName": "Tea", "productPrice": 100 },
{ "_id": ObjectId("61444c1a0e945f654c1c4931"), "productName": "Koffee", "productPrice": 200 } ] }


What I have tried:

I'm trying to get a product from each store, with the maximum price: 


db.driverStores.aggregate([ ... {$unwind:"$listProducts" }, ... {$match : { "listProducts.productPrice" : { $ne : 0 } } }, ... {$group : { _id : { storeName : "$storeName"}, ... MAXPRICE_Products : { $max : "$listProducts.productPrice"}, ... $addFields: { Name: {$add: ["$listProducts.productName" ] }} ... }} ... ])


but I get "errmsg": "The field '$addFields' must be an accumulator object"

In this case, how can you use accumulator to get the name of the product with the highest price?
Posted
Updated 21-Sep-21 22:12pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900