mongodb 如何在mongodb中查询子对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4762947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:56:45  来源:igfitidea点击:

how to query child objects in mongodb

mongodb

提问by Justin

I'm new to mongodb and am trying to query child objects. I have a collection of States, and each State has child Cities. One of the Cities has a Name property that is null, which is causing errors in my app. How would I query the State collections to find child Cities that have a name == null?

我是 mongodb 的新手,正在尝试查询子对象。我有一个州的集合,每个州都有子城市。其中一个城市的 Name 属性为 null,这会导致我的应用程序出错。我将如何查询 State 集合以查找具有 name == null 的子城市?

回答by Theo

If it is exactly null(as opposed to not set):

如果完全正确null(而不是未设置):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

(但正如 javierfp 指出的那样,它还匹配根本没有城市数组的文档,我假设它们确实如此)。

If it's the case that the property is not set:

如果是未设置属性的情况:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

我已经用这两个插入创建的集合测试了上述内容:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $orquery:

第一个查询找到第一个状态,第二个查询找到第二个状态。如果您想通过一个查询找到它们,您可以进行$or查询:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})

回答by Javier Ferrero

Assuming your "states" collection is like:

假设你的“状态”集合是这样的:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

查找具有空城市的州的查询将是:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistaketo query for nulls as:

查询空值是一个常见的错误

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

因为此查询将返回所有缺少密钥的文档(在我们的示例中,它将返回西班牙和法国)。因此,除非您确定该键始终存在,否则您必须检查该键是否存在于第一个查询中。