从与mongodb中的条件匹配的多个子文档中获取字段

时间:2013-01-21 06:43:38

标签: mongodb

下面的

是我在mongodb的收藏 -

{
    "_id" : ObjectId("50f69176904e1d66affec20d"),
    "connections" : [
    {
        "id" : "50f651a3b58bba7fbec2f222"
    },
    {
        "group" : "Roomies",
        "users" : [
        {
            "id" : "50f651a3b58bba7fbec2f222"
        },
        {
            "id" : "50f651b8b58bba7fbec2f223"
        }
        ]
    },
    {
        "group" : "College",
        "users" : [
        {
            "id" : "50f651b8b58bba7fbec2f223"
        },
        {
            "id" : "50f651a3b58bba7fbec2f222"
        }
        ]
    },
    {
        "group" : "Work",
        "users" : [
        {
            "id" : "50f651a3b58bba7fbec2f222"
        }
        ]
    },
],
"email" : "arunko350@gmail.com",
"name" : "Arun"
}

这里我想获得id = 50f651a3b58bba7fbec2f222所在的所有组名。请帮我。我正在浏览2天的解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用MongoDB 2.2的aggregation framework执行此操作。在shell中:

db.test.aggregate([
      // Duplicate the docs, one per connections array element.
      {$unwind: '$connections'},
      // Only include the docs with the specified user id
      {$match: {'connections.users.id': '50f651a3b58bba7fbec2f222'}},
      // Bring group out to the only top level field and exclude _id
      {$project: {_id: 0, group: '$connections.group'}}
])

输出:

{
  "result": [
    {
      "group": "Roomies"
    },
    {
      "group": "College"
    },
    {
      "group": "Work"
    }
  ],
  "ok": 1
}

答案 1 :(得分:-1)

$ elemMatch运算符可用于对数组元素进行投影。

  

http://docs.mongodb.org/manual/reference/projection/elemMatch/#_S_elemMatch

以下应该没问题

var projection = {"connections.group":1, "connections":{$elemMatch: {"users.id":"507c35dd8fada716c89d0013"}}}

db.collection.find( {{"connections.users.id": "507c35dd8fada716c89d0013"}}, projection);