简体   繁体   English

如何通过子文档两个字段的值查找文档?

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

I have 4 records in my db 我的数据库中有4条记录

{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. 并且我只想查找c字段的任何数组元素同时具有d等于1e等于0的文档。 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. 数据库返回3个结果,其中cd = 1ce = 0 ,但对于同一子文档则不同。 How can I form the request based on my criteria which will return me only the first and third record? 如何根据我的标准形成请求,该条件将仅返回第一条和第三条记录?

Use $elemMatch . 使用$ 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. 其他不匹配的数组元素将不会显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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