deepujain deepujain - 1 year ago 112
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.


{ "_id" : "", "
className" : "UserAgents",
"userAgents" : [
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-CA; rv: Gecko/2008120122 Firefox/3.0.5",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv: 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: 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


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


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 Source

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":""});
var count = document.userAgents.length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download