Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying internal array size in MongoDB

Consider a MongoDB document in users collection:

{ username : 'Alex', tags: ['C#', 'Java', 'C++'] } 

Is there any way, to get the length of the tags array from the server side (without passing the tags to the client) ?

Thank you!

like image 951
Zaur Nasibov Avatar asked Jul 17 '11 09:07

Zaur Nasibov


People also ask

How do I find the length of an array in MongoDB?

The $size operator in MongoDB is used to fetch the document that has an array field of a specific size.

How do I see the size of a file in MongoDB?

To get the exact size (in bytes) of the document, stick to the Object. bsonsize() function.

How do I test an array 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 $project in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. The $project specifications have the following forms: Form. Description.


2 Answers

if username Alex is unique, you can use next code:

db.test.insert({username:"Alex", tags: ['C#', 'Java', 'C++'] }); db.test.aggregate(   {$match: {username : "Alex"}},    {$unwind: "$tags"},   {$project: {count:{$add:1}}},   {$group: {_id: null, number: {$sum: "$count" }}} ); { "result" : [ { "_id" : null, "number" : 3 } ], "ok" : 1 } 
like image 131
xmm.dev Avatar answered Oct 02 '22 03:10

xmm.dev


Now MongoDB (2.6 release) supports $size operation in aggregation.

From the documentation:

{ <field>: { $size: <array> } } 

What you want can be accomplished as following with either by using this:

db.users.aggregate(    [       {          $group: {             _id: "$username",             tags_count:  {$first: {$size: "$tags" }}          }       }    ] ) 

or

db.users.aggregate(    [       {          $project: {             tags_count: {$size: "$tags"}          }       }    ] ) 
like image 33
anvarik Avatar answered Oct 02 '22 01:10

anvarik