V
V
Vitaly Gusev2021-09-22 10:28:46
MongoDB
Vitaly Gusev, 2021-09-22 10:28:46

How to use accumulator in MongoDB?

I have a collection of driverStores where each Store has a collection Product

{ "_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": "Coffee", "productPrice": 200 } ] }

I'm trying to get a product from each store with a 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 an error: "errmsg": "The field '$addFields' must be an accumulator object"
How can the accumulator be used in this case to get the name of the product with the highest price?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question