php - 在不知道 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”的情况下做同样的事情。
解决方案
这应该为您指明正确的方向:
db.collection.aggregate({
$addFields: {
"userTransformed": {
$objectToArray: "$user" // transform "user" field into key-value pair
}
}
}, {
$match: {
"userTransformed.v.funny": "sure" // just filter on the values
}
})
坦率地说,这对于大量文档来说不会很快,但没有其他方法。此查询不会使用索引。如果你想变得更快,你需要改变你的文档结构。
推荐阅读
- javascript - 如何在使用 javascript 过滤表格后保持 TD 标头处于活动状态
- r - r 每周查找到每日数据集
- javascript - 无法使用 mongoose 更新子文档
- jenkins - 在詹金斯声明性管道中具有插值的条件环境变量
- reactjs - 无法从 Firebase 数据库读取数据
- r - 获取r中字符串中模式的重叠位置
- pyspark - 如何将免费日期范围添加到 pyspark df
- python - NoReverseMatch 错误。未找到“...”的反向
- firebase - 如何在颤动中模拟 FirebaseApp
- mysql - 锁定MySQL选择行直到对其运行UPDATE?