英文:
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"
    ]
  }
}
这是另一个版本,保持了您的原始架构。您可以看到它更加复杂,因为涉及到$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"
      ]
    },
    
  }
Here is another version that keeps your original schema. You can see it is much more complex as it involves $objectToArray
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论