Siva Kannan
Siva Kannan

Reputation: 2481

Get matching objects in an object Array from mongodb collections?

The below is the collection named testing which i am working on and I need to get all the persons who is having the DOB of "24-04-1973"

 {
        "year": "1973",
        "allPersons": [
            {
                "name": "First guy",
                "DOB": "24-04-1973"
            },
            {
                "name" : "Second guy",
                "DOB":  "02-12-1973"
            }     
            {
                "name": "Third guy",
                "DOB": "13-01-1973"
            },
            {
                "name": "Fourth guy",
                "DOB": "24-04-1973"
            },
            {
                "name": "Fifth guy",
                "DOB": "24-04-1973"
            },
        ]
    }

But I am only able to get the first object from the allPersons Array through the below query

 db.testing.find(
       {
              "allPersons.DOB":"24-04-1973"
       },
       {
              _id:0,"allPersons":
              {
                     $elemMatch:
                     {
                            "DOB":'24-04-1973'
                     }
              }
       }
).pretty();

Result of above Query

{
        "allPersons" : [
                {
                        "name" : "First guy",
                        "DOB" : "24-04-1973"
                }
        ]
}

But the result i am expecting to get is to have all the persons who have the DOB of "24-04-1973" like below

  {
            "allPersons" : [
                    {
                            "name" : "First guy",
                            "DOB" : "24-04-1973"
                    },
                    {        
                            "name" : "Fourth guy",
                            "DOB" : "24-04-1973"
                    },
                    {
                            "name" : "Fifth guy",
                            "DOB" : "24-04-1973"
                    }
            ]
    }

Does anybody know the correct query to generate the above kind of result

mongo Db version 2.6.11

I am new to this, Excuse if it's silly

Upvotes: 0

Views: 719

Answers (1)

Saleem
Saleem

Reputation: 9008

Try following script:

db.doc.aggregate([
    {$unwind:"$allPersons"},
    {$match:{"allPersons.DOB":"24-04-1973"}},
    {$group:{_id:{id:"$_id", year:"$year"}, allPersons:{$push:"$allPersons"}}},
    {$project:{_id:0, allPersons:1}}  
])

It will emit:

{ 
    "allPersons" : [
        {
            "name" : "First guy", 
            "DOB" : "24-04-1973"
        }, 
        {
            "name" : "Fourth guy", 
            "DOB" : "24-04-1973"
        }, 
        {
            "name" : "Fifth guy", 
            "DOB" : "24-04-1973"
        }
    ]
}

Upvotes: 2

Related Questions