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?