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!
The $size operator in MongoDB is used to fetch the document that has an array field of a specific size.
To get the exact size (in bytes) of the document, stick to the Object. bsonsize() function.
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.
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.
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 }
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"} } } ] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With