2

Possible Duplicate:
Querying internal array size in MongoDB

I have a document which contains an array category. I just want to know how many items there are in category. All I could find in the documentation is how to count the number of top level documents.

{
 "_id": {
     "$oid": "4e73a30466ca1a1f56000001"
    },
 "category": [
     "Food",
     "Entertainment"
    ]
}
0

2 Answers 2

3

Add new field to hande category size. It's a usual practice in mongo world.

Sign up to request clarification or add additional context in comments.

Comments

2

To find a single example element in a collection callend mycollection:

db.mycollection.find().limit(1)[0];

To get the number of elements in the arry category:

db.mycollection.find().limit(1)[0].category.length;

Or:

var elem = db.mycollection.find().limit(1)[0];
elem.category.length;

2 Comments

Doesn't that return the array, which I then count locally? Wouldn't it be better to somehow use the mongodb count() method and have the database just return the count without having the fetch the entire object and then count it locally?
Well, I did added to much stuff around the actual answer to complete it. So the short answer to your given question is only: elem.category.length;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.