MongoDB - 查找与未知字段键的特定条件匹配的文档

2024-01-15

如何查询 MongoDB 集合以查找具有如下结构的文档?这些文档有一个名为thing这是一个子文档,该字段的键是 ID 号的形式,它将一般不为人所知由编写查询的人(使点表示法变得困难,我认为不可能)。

{   
"_id" : 3,
"_id2" : 234,
"thing": 
    {
    "2340945683":
        {"attribute1": "typeA",
         "attribute2": "typeB",
         "attribute3": "typeA"
        },

    "349687346":
        {"attribute1": "typeC",
         "attribute2": "typeB",
         "attribute3": "typeA"
        }           
    },      
    "username": "user1"
}

假设我想设置一个过滤器,仅当其中的某个或多个字段时才会返回文档thing有条件"attribute1" : "typeC"?

我需要类似的东西

db.collection.find( {thing.ANY_FIELD: $elemMatch:{"attribute1":"typeC"}})

你需要从$objectToArray https://docs.mongodb.com/manual/reference/operator/aggregation/objectToArray/index.html动态读取您的密钥。然后你可以$map https://docs.mongodb.com/manual/reference/operator/aggregation/map/index.html属性以及$anyElementTrue https://docs.mongodb.com/manual/reference/operator/aggregation/anyElementTrue/index.html检测是否有任何嵌套字段thing含有{"attribute1":"typeC"}:

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $anyElementTrue: {
                    $map: {
                        input: { $objectToArray: "$thing" },
                        in: { $eq: [ "$$this.v.attribute1", "typeC" ] }                         
                    }
                }
            }
        }
    }
])

蒙戈游乐场 https://mongoplayground.net/p/Dvt42QaNThZ

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB - 查找与未知字段键的特定条件匹配的文档 的相关文章

随机推荐