我是mongodb的新手,正在尝试查询子对象。我有一个州的集合,每个州都有子城市。其中一个城市的Name属性为null,这会导致我的应用程序出现错误。如何查询州集合以查找名称为== null的子城市?
发布于 2011-01-22 04:51:46
如果它恰好是null
(而不是not ):
db.states.find({"cities.name": null})
(但正如javierfp指出的那样,它也会匹配根本没有城市数组的文档,我假设它们是有的)。
如果是未设置属性的情况:
db.states.find({"cities.name": {"$exists": false}})
我已经用用这两个插入创建的集合测试了上面的内容:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
第一个查询查找第一个状态,第二个查询查找第二个状态。如果你想用一个查询同时找到它们,你可以做一个$or
查询:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
https://stackoverflow.com/questions/4762947
复制相似问题