0

In MongoDB, the aggregate query below gives the average price per product-category, where business-name is "Foobar Inc".

var match = { $match: {"businessName": "FooBar Inc"}, ;

var group = { $group: { _id: "$productCategory", total: { $avg: "$price" }}}

var results = await db.aggregate("productsCollection", limit, match, group);

Example object from productCollection:

{"businessName": "FooBar Inc.",  "productCategory": "toys", "price":88}

Output:

 [{"_id": "shoes", "total":97}, {"_id": "toys", "total":77}]

However, I want to replace "FooBar Inc." with a variable, so that multiple average-prices are returned.

The data returned would be something like:

shoes, Foobar Inc.: average price 97

toys, Foobar Inc.: average price 88

shoes, Quux Ltd.: average price 68

toys, Quux Ltd.: average price 101

I could run multiple aggregate queries, but is there away to do this in a single query?

2
  • Can you add sample object from productsCollection? Commented Jul 29, 2019 at 9:21
  • I did so and also simplified the output Commented Jul 29, 2019 at 9:32

1 Answer 1

1

You need to group by both productCategory and businessName:

var group = { $group: { 
    _id: {category: "$productCategory", name: "$businessName"}, 
    total: { $avg: "$price" }
}}

and no $match stage of course.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.