Search code examples
mongodbmongodb-querysubdocument

MongoDB query array of subdocuments


I have researched throughly before posting this question but I could not find an accurate solution. I have the below structure

stname: "SC",
dob : "1985",
education {[
            {name : Lancaster,
             year : 2013},

            {name : Manchester, 
             year : 2001, 
             grad : 2004},

            {name : Gambia, 
             year : 2001, 
             grad : 2011}
         ]}

So I want to return only documents that have grad fields. So the last two documents should be returned.

I tried the following queries but to no avail

db.applicants.find({"education" : { $elemMatch : {"grad" : {$exists : true}}}}, {"name":1, "education.grad" : 1}).pretty()

returns only the first match as shown below,the first document is empty

{
    "_id" : ObjectId("574dd5fcbda73af19e361a3f"),
    "name" : "SC",
    "education" : [
        {

        },
        {
            "grad" : "2004"
        },
        {
            "grad" : "2011"
        }
    ]
}

Also the below query gives you similar results, that is an empty document where ever grad field is not available.

db.applicants.find({"education.grad" : { $exists : true}}, {"education.grad" : {$exists : true}, "education.grad" : 1, name : 1 , dob : 1}).pretty()

Solution

  • UPDATE ANSWER:

    db.applicants.aggregate({$unwind: "$education"}, 
    {$match: {"education.grad":{$exists: true}}}, 
    {$project: {"education.name": 1, "education.grad": 1, "_id": 0}})
    

    This will return two records, no empty documents.