Querying internal array size in MongoDB

Zaur Nasibov picture Zaur Nasibov · Jul 17, 2011 · Viewed 34.2k times · Source

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!

Answer

xmm.dev picture xmm.dev · Dec 15, 2012

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 }