gpt4 book ai didi

mongodb - 如何在mongodb中查询子对象

转载 作者:IT老高 更新时间:2023-10-28 11:14:19 32 4
gpt4 key购买 nike

我是 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}}
]})

关于mongodb - 如何在mongodb中查询子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762947/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com