Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query based on count of embedded document

Suppose I have:

Order: {_id: ..., items: [...]}

How to filter orders which have item number greater than 5?

like image 938
Gelin Luo Avatar asked Jan 16 '11 11:01

Gelin Luo


People also ask

How do I count the number of documents in MongoDB?

n = count( conn , collection ,Query= mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

How do I query nested data in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

Where is total count in MongoDB?

count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.


1 Answers

You cann't query by size of embed collection, you need to create field with size of collection for such needs(mongo db documentation):

The $size operator matches any array with the specified number of elements. The following example would match the object {a:["foo"]}, since that array has just one element:

db.things.find( { a : { $size: 1 } } );

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

like image 91
Andrew Orsich Avatar answered Sep 25 '22 02:09

Andrew Orsich