2

以下是我在 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 天的解决方案。

4

2 回答 2

2

您可以使用 MongoDB 2.2 的聚合框架来做到这一点。在外壳中:

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
}
于 2013-01-21T15:57:19.407 回答
-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);
于 2013-01-21T08:35:45.033 回答