How count embedded document?

1,087 views
Skip to first unread message

Raitucarp

unread,
Dec 29, 2012, 2:02:47 AM12/29/12
to mongod...@googlegroups.com
I have a collection:

[
  {
    "title": "zaya",
    "text": "zaya",
    "_id": "50dd4993410d3b1804000001",
    "__v": 0,
    "time": "2012-12-28T07:26:11.999Z",
    "reports": [],
    "votes": []
  },
  {
    "title": "zaya",
    "text": "zaya",
    "_id": "50dd521749a49a5413000001",
    "__v": 0,
    "time": "2012-12-28T08:02:31.599Z",
    "reports": [],
    "votes": []
  },
  {
    "_id": "50dd494910aa935c0a000001",
    "title": "Barrbaba",
    "text": "yayaya",
    "aba": [
      {
        "position": "neutral",
        "name": "arara"
      },
      {
        "position": "pro",
        "name": "galaga"
      }
    ],
    "__v": 0,
    "time": "2012-12-28T07:24:57.853Z",
    "reports": [],
    "votes": []
  },
  {
    "title": "zaya",
    "text": "zaya",
    "_id": "50de8fbba01a01b812000001",
    "__v": 0,
    "time": "2012-12-29T06:37:47.607Z",
    "reports": [],
    "votes": [
      {
        "name": "arara",
        "vote": "up"
      },
      {
        "name": "yasama",
        "vote": "up"
      },
      {
        "name": "gangnam",
        "vote": "down"
      }
    ]
  }
]

How to count votes? In this case, only Id 50de8fbba01a01b812000001 has votes

Raitucarp

unread,
Dec 29, 2012, 2:04:07 AM12/29/12
to mongod...@googlegroups.com
_id 50de8fbba01a01b812000001 has 3 votes, and how to do that with mongo?

William Zola

unread,
Dec 31, 2012, 11:04:35 AM12/31/12
to mongod...@googlegroups.com
You can do this with the MongoDB aggregation framework.

Since it's not clear exactly what you want to count, or how you want the results displayed, I can't offer you example code.

 -William 

Arthur Neves

unread,
Dec 31, 2012, 11:18:17 AM12/31/12
to mongod...@googlegroups.com
You could count using a simple map/reduce or use the aggregations framework to count as well. However if you want to count just to be able to query on them, you dont need to count, you can use the $size operator : http://docs.mongodb.org/manual/reference/operators/#_S_size 
something like this:
db.collection.find( { votes: { $size: 2 } } );
Reply all
Reply to author
Forward
0 new messages