我是 mongodb 的新手,正在尝试查询子对象。我有一个州的集合,每个州都有子城市。其中一个城市的名称属性为空,这导致我的应用程序出错。我将如何查询 State 集合以查找名称 == null 的子城市?
最佳答案
如果它恰好是 null
(相对于未设置):
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/