如何查询mongodb中的子对象

我是新来的mongodb,并试图查询子对象。 我有一个国家的集合,每个国家有儿童城市。 其中一个城市有一个名称属性为空,这是我的应用程序中导致错误。 我将如何查询州集合来查找具有名称== null的子城市?

如果它完全为null (而不是未设置):

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

(但是正如javierfp指出的那样,它也匹配没有任何城市的文件,我假设他们这样做)。

如果属性没有设置的话:

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

我已经使用这两个插入创build的集合testing了上面的代码:

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

第一个查询find第一个状态,第二个查询find第二个查询。 如果你想通过一个查询find它们,你可以做一个$or查询:

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

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

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

查找空城市的查询将是:

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

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

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

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