gpt4 book ai didi

mongodb - 如何检查对象嵌套属性是否存在?

转载 作者:可可西里 更新时间:2023-11-01 09:59:44 26 4
gpt4 key购买 nike

我有一个对象 Document,带有嵌套的 Properties(名称、值)集合。

现在我想查找 "Properties.Name"= "SomePropertyName" 不存在的文档。

我试过了,但只有当属性存在但具有 null 值时它才有效:

{"Properties":{"$elemMatch":{"Name":"SomePropertyName", "Value.0":{"$exists":false}}}}

我尝试了一些疯狂的 $ne$exists 组合,这些组合应该可以恢复我的关系数据库查询体验,但没有帮助。

文档示例:

[
{
"_id": "Document1",
"Properties": [
{
"Name": "SomeName",
"Value": [
"value1",
"value2"
]
},
{
"Name": "Property2",
"Value": [
"value3"
]
}
]
},
{
"_id": "Document2",
"Properties": [
{
"Name": "Property2",
"Value": [
"value3"
]
},
{
"Name": "Property3",
"Value": null
}
]
},
{
"_id": "Document3",
"Properties": [
{
"Name": "SomeName",
"Value": null
},
{
"Name": "Property2",
"Value": [
"value3"
]
},
{
"Name": "Property3",
"Value": null
}
]
}
]

查询应该返回 Document2Document3(查询“SomeName”属性)

如何查询属性不存在或具有 null 值的文档?

最佳答案

我相信这是您想要的查询:

db.prop.find({$or: [
... {"Properties.Name":{$ne:"SomeName"}},
... {"Properties":{$elemMatch:{"Name":"SomeName","Value":null}}}
... ] })

这表示您需要所有未设置“SomeName”的文档(即不存在的文档等于“SomeName”)以及所有名称为“SomeName”且同时为“Value”的文档为空。

我在你的例子中试过了,得到了文档 2 和 3。

关于mongodb - 如何检查对象嵌套属性是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959059/

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