【问题标题】:Finding documents having specific values in subdocuments in MongoDB在 MongoDB 的子文档中查找具有特定值的文档
【发布时间】: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"}]}
]
  1. 我们怎样才能得到locations子文档中只有country: "Germany"的所有文档的name字段?

    示例:使用上面的示例集合items,然后执行上面的查询应该返回[{name: "D"}]

  2. 我们如何获取所有带有locations 子文档但没有country: Francecountry: "Germany"(或两者)作为元素的文档的name 字段?

    示例:使用上面的示例集合items,然后执行上面的查询应该返回[{name: "B"}, {name: "E"}]

我已经阅读了文档,并尝试了很多方法,最终我使用了两个步骤来处理它。使用我提出的最具体的查询进行查询,然后通过以编程方式循环遍历文档(数组)来过滤不需要的文档。我更想知道之前的任何一个查询是否可以通过单个查询直接实现。

注意:文档/查询只是示例,我处理的文档/查询是不同的。

【问题讨论】:

  • 1-db.test.find({"locations": [{ "country" : "Germany" }]})
  • 只有在我们假设locations 只包含一个键/值country: "Germany" 时才有效。如果还有其他键/值对,就不行了。

标签: mongodb find mongodb-query


【解决方案1】:

我们如何在位置子文档中获取所有只有国家:“德国”的文档的名称字段?

$size 运算符将派上用场:

db.foo.find({locations:{$size:1}, "locations.country":"Germany"})

我们如何获取所有位置子文档的名称字段不包含国家:法国或国家:“德国”(或两者)作为元素?

$nin 运算符将派上用场:

db.foo.find({"locations.country":{$nin:["Germany", "France"]}})

【讨论】:

  • 很好的答案。我是否假设如果我只想获取同时具有“德国”和“法国”两个位置的文档,那么我会这样做:db.items.find({locations:{$size:2}, "locations.country": {$in:["Germany","France"]}})
  • 在这种情况下,您需要使用$all 运算符来匹配给定数组中的所有元素:db.items.find({locations:{$size:2}, "locations.country": {$all:["Germany","France"]}})
  • 感谢阿南德的帮助。
猜你喜欢
  • 2015-09-02
  • 2016-06-18
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多