简体   繁体   中英

How to find documents by values of two fields of sub-document?

I have 4 records in my db

{c: [{d:1, e:0}, {d:2, e:0}]}    
{c: [{d:1, e:1}, {d:2, e:0}]}    
{c: [{d:1, e:0}, {d:2, e:1}]}
{c: [{d:1, e:1}, {d:2, e:1}]}

and I want to find only the document where any of the c field's array elements has d being equal to 1 and e being equal to 0 at the same time. If I execute query such like:

db.b.find({"c.d": 1, "c:e": 0})

or

db.b.find({$and: [{"c.d": 1}, {"c:e": 0}]})

database returns 3 results where cd = 1 and ce = 0 , but not for the same sub-document. How can I form the request based on my criteria which will return me only the first and third record?

Use $elemMatch . It allows you to specify the values matching in one array element.

db.b.find({ c: {$elemMatch: { d: 1, e: 0 } } })

That gives you the whole document that has the matching element. If you want to only see the matching array element in the response, use projection on the field, as in:

db.b.find({ c: {$elemMatch: { d: 1, e: 0 } } },{ "c.$": 1 })

And other non-matching array elements will not be shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM