mongodbnested-documents

MongoDB query nested document fields simultaneously


Having document in collection test as follow:

{a:2, list:[{lang:"en", value:"Mother"}, {lang:"de", value:"Mutter"}] }

When I query:

db.test.find({"list.lang":"de", "list.value": "Mother" })

I'm expecting to get nothing, but on reason that exist document with 2 nested entries that satisfies total condition MongoDB resolves {a:2}

How to fix query to retrieve only documents where both inner fields satisfies to specified condition simultaneously?


Solution

  • Using $elemMatch:

    db.test.find({ "list": { "$elemMatch": {"lang":"de", "value": "Mother" } } })
    

    Using $all:

    db.test.find({ "list": { "$all": [{"lang":"de", "value": "Mother" }] } })