deepujain deepujain - 5 months ago 21
JSON Question

How to count number of elements in json array stored in MongoDB collection

I have mongodb collection "mongocollection", each document in the collection consists of two columns, first a string "cid" which is the id of the collection and second is a json array.

Ex:

{ "_id" : "domain.com", "
className" : "UserAgents",
"userAgents" : [
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-CA; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.6) Gecko/20100628 Ubuntu/10.04 (lucid) Firefox/3.6.6 (.NET CLR 3.5.30729)",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.2) Gecko/20090803 Firefox/3.5.2 Slackware",
"Mozilla/5.0 (X11; U; Linux x86_64) Gecko/2008072820 Firefox/3.0.1"
]
}


From mongo cmd line, i can get the contents of a given document within a collection as

db.CorruptUserAgents.find({"_id":"domain.com"}).pretty();


How do i get the number of elements in a given array of a given document. Ex

SOMETHING.count();
100


Is it possible to do this via cmd line ?
I know i can get the document, iterate over the array and count the elements, but i want to do this from cmd line.

Answer

You can use .findOne() instead since you are looking up by _id, it will return a single document.

So you can simply do something like this:

var document = db.CorruptUserAgents.findOne({"_id":"domain.com"});
var count = document.userAgents.length;