Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Count of matching nested array elements

Tags:

mongodb

I've got a simple parent child object stored as a document in MongoDB. Something simplistic like Order/OrderItems. (Order has an array of OrderItem)

What I'd like to do is query for a count of Order Items where they meet a set of criteria.

Example: In Order "999" find out how many order items had a quantity of 3.

db.collection.find( {OrderId:999, "OrderItems.QuantityOrdered":3} ).count();

The way this query works is it returns "1" because if it matches at least one OrderItem inside the array it will return the count of Orders matched.

How can I query for how many "OrderItems" matched?:

like image 900
whitez Avatar asked May 25 '26 02:05

whitez


1 Answers

There's no direct way of return this sort of count with an embedded document. With this sort of ad-hoc count, your best bet is to return the document and do the count from the application.

If you want to perform this kind of count for a large number of orders, you could use map-reduce, which will output the results to a new collection.

like image 72
Kyle Banker Avatar answered May 27 '26 19:05

Kyle Banker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!