如何在mongodb中查询子对象 [英] how to query child objects in mongodb
问题描述
我是mongodb的新手,正在尝试查询子对象.我有一个州的集合,每个州都有一个儿童城市.其中一个城市的Name属性为null,这会导致我的应用程序出现错误.我将如何查询州集合以查找名称为== null的子城市?
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?
推荐答案
如果恰好是null
(而不是未设置):
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(但正如javierfp所指出的,它也匹配完全没有城市数组的文档,我假设它们确实匹配).
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
如果未设置该属性,则:
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"}]})
第一个查询找到第一个状态,第二个查询找到第二个状态.如果要通过一个查询找到它们两者,可以进行$or
查询:
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 $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
这篇关于如何在mongodb中查询子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!