首页 > 解决方案 > 在不知道 MongoDB 中键的情况下使用关联数组查找值

问题描述

我有一个具有这种结构的文档:

{"user":{
     "nice":{
         "funny":"sure"
             }
     ,
     "notnice":{
         "funny":"maybe"
             }
     }
}

我知道键“user”、“funny”和值“sure”和“maybe”,但我不知道“nice”和“notnice”。

如何进行优化查询以搜索多个文档。

例如,如果我想在知道中间键的情况下搜索“确定”值:

$document = $users->findOne([
'$or' => [
        ['user.nice.funny' => 'sure'],
        ['user.notnice.funny' => 'sure']
    ]
]

);

但是我如何在不知道“nice”和“notnice”的情况下做同样的事情。

标签: phpmongodbmongodb-query

解决方案


这应该为您指明正确的方向:

db.collection.aggregate({
    $addFields: {
        "userTransformed": {
            $objectToArray: "$user" // transform "user" field into key-value pair
        }
    }
}, {
    $match: {
        "userTransformed.v.funny": "sure" // just filter on the values
    }
})

坦率地说,这对于大量文档来说不会很快,但没有其他方法。此查询不会使用索引。如果你想变得更快,你需要改变你的文档结构。


推荐阅读