如何检查对象嵌套属性的存在?

Bri*_*kim 2 mongodb

我有一个Document嵌套Properties(Name,Value)集合的对象.

现在我想找到"Properties.Name" = "SomePropertyName"不存在的文件.

我试过这个,但它只有在属性存在但null有价值时才有效:

{"Properties":{"$elemMatch":{"Name":"SomePropertyName", "Value.0":{"$exists":false}}}}
Run Code Online (Sandbox Code Playgroud)

我尝试了一些狂野的$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
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

查询应返回Document2Document3(查询"SomeName"属性)

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

Asy*_*sky 5

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

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

这表示您希望所有未设置"SomeName"的文档(即没有存在的文档等于"SomeName")以及Name为"SomeName"且同时"Value"为null的所有文档.

我在你的例子上试了一下,得到了文件2和3.