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"
    ]
}
Community
  • 1
  • 1
lmirosevic
  • 15,787
  • 13
  • 70
  • 116

2 Answers2

3

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

Igorekk
  • 256
  • 1
  • 8
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;
Dag
  • 10,079
  • 8
  • 51
  • 74
  • 1
    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? – lmirosevic Sep 17 '11 at 17:11
  • 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;` – Dag Sep 18 '11 at 20:54