ArunKolhapur
ArunKolhapur

Reputation: 6925

Get fields from multiple sub-documents that match a condition in mongodb

below is my collection in 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" : "[email protected]",
"name" : "Arun"
}

Here i want to get all the group names in which id = 50f651a3b58bba7fbec2f222 exists. Please help me. I am browsing for 2 days for the solution.

Upvotes: 2

Views: 5633

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311895

You can do this with MongoDB 2.2's aggregation framework. In the 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'}}
])

outputs:

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

Upvotes: 2

cubbuk
cubbuk

Reputation: 7920

$elemMatch operator can be used for projection on array elements.

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

The following should be ok

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

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

Upvotes: -1

Related Questions