Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: count the number of items in an array

I have a collection where every document in the collection has an array named foo that contains a set of embedded documents. Is there currently a trivial way in the MongoDB shell to count how many instances are within foo? something like:

db.mycollection.foos.count() or db.mycollection.foos.size()?

Each document in the array needs to have a unique foo_id and I want to do a quick count to make sure that the right amount of elements are inside of an array for a random document in the collection.

like image 353
randombits Avatar asked Jan 27 '14 17:01

randombits


People also ask

How do I find the number of items in MongoDB?

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

How can I find the value of 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.

What is $size in MongoDB?

The $size operator in MongoDB is used to fetch the document that has an array field of a specific size. The $size only deals with arrays and accepts only numeric values as a parameter.


1 Answers

In MongoDB 2.6, the Aggregation Framework has a new array $size operator you can use:

> db.mycollection.insert({'foo':[1,2,3,4]}) > db.mycollection.insert({'foo':[5,6,7]})  > db.mycollection.aggregate([{$project: { count: { $size:"$foo" }}}]) { "_id" : ObjectId("5314b5c360477752b449eedf"), "count" : 4 } { "_id" : ObjectId("5314b5c860477752b449eee0"), "count" : 3 } 
like image 138
Stennie Avatar answered Sep 21 '22 09:09

Stennie