在数组中查找动态对象键中对象值的MongoDB字符串匹配

huangapple go评论59阅读模式
英文:

MongoDB find string match in object value from an array with dynamic object key

问题

我有这样的文档结构,在字段post中有动态对象键名,为了简单起见,它们被命名为dynaimcX。

我如何筛选那些包含字段image的文档?

英文:

i have this document structure where i have dynamic object keys names in field post named as dynaimcX for the sake of simplicity.

How can i filter those documents that contains field image?

[
    {
        "_id": "63385ece9801130700fb28e2",
        "post": {
            "dynamicone": [
                {
                    "image": "image1.png"
                }
            ],
            "commments": [
                "Lorem ipsum"
            ]
        },
    },
    {
        "_id": "61702dd8d7bc4106004627f2",
        "post": {
            "dynamictwo": [
                {
                    "image": "image2.png"
                }
            ],
            "commments": [
                "Lorem ipsum"
            ]
        },
    },
    {
        "_id": "61f05a9800b2210700fe3fa3",
        "post": {
            "commments": [
                "Lorem ipsum"
            ]
        },
    },
    {
        "_id": "61701eb47c6bb50700e36c16",
        "post": {
            "commments": [
                "Lorem ipsum"
            ]
        },
    },
]

答案1

得分: 0

使用动态值被视为一种反模式,并为查询引入了不必要的复杂性。您可以使用适当的架构做一些更简单的事情:

db.collection.find({
  "post.value": {
    $exists: true
  }
})

提议的架构:

{
  "_id": "63385ece9801130700fb28e2",
  "post": {
    "key": "dynamicone",
    "value": [
      {
        "image": "image1.png"
      }
    ],
    "comments": [
      "Lorem ipsum"
    ]
  }
}

Mongo Playground


这是另一个版本,保持了您的原始架构。您可以看到它更加复杂,因为涉及到$objectToArray

英文:

Using dynamic value is considered an anti-pattern and introduces unnecessary complexity to queries. You can do something much simpler with proper schema:

db.collection.find({
  "post.value": {
    $exists: true
  }
})

schema proposed:

 {
    "_id": "63385ece9801130700fb28e2",
    "post": {
      "key": "dynamicone",
      "value": [
        {
          "image": "image1.png"
        }
      ],
      "commments": [
        "Lorem ipsum"
      ]
    },
    
  }

Mongo Playground


Here is another version that keeps your original schema. You can see it is much more complex as it involves $objectToArray

huangapple
  • 本文由 发表于 2023年2月14日 03:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定