【发布时间】:2015-02-13 19:30:24
【问题描述】:
在 MongoDB 中,假设我们有一个集合 items,其中包含以下示例数据:
[
{name: "A", locations: [{country: "USA"}, {country: "Germany"}]},
{name: "B", locations: [{country: "USA"}],
{name: "C", locations: [{country: "France"}, {country: "Germany"}]},
{name: "D", locations: [{country: "Germany"}]},
{name: "E", locations: [{country: "USA"}, {country: "UK"}]}
]
-
我们怎样才能得到
locations子文档中只有country: "Germany"的所有文档的name字段?示例:使用上面的示例集合
items,然后执行上面的查询应该返回[{name: "D"}] -
我们如何获取所有带有
locations子文档但没有country: France或country: "Germany"(或两者)作为元素的文档的name字段?示例:使用上面的示例集合
items,然后执行上面的查询应该返回[{name: "B"}, {name: "E"}]
我已经阅读了文档,并尝试了很多方法,最终我使用了两个步骤来处理它。使用我提出的最具体的查询进行查询,然后通过以编程方式循环遍历文档(数组)来过滤不需要的文档。我更想知道之前的任何一个查询是否可以通过单个查询直接实现。
注意:文档/查询只是示例,我处理的文档/查询是不同的。
【问题讨论】:
-
1-db.test.find({"locations": [{ "country" : "Germany" }]})
-
只有在我们假设
locations只包含一个键/值country: "Germany"时才有效。如果还有其他键/值对,就不行了。
标签: mongodb find mongodb-query