mongodb - mongodb查询具有未知属性的第三级
问题描述
我需要在 mongodb 中执行查询。文件存储如下
{
"_id": "5b506440a7769100817265b2",
"zones": [
"London",
"Berlin",
"Rome"
],
"width": 100,
"price_list_id": 2,
"heights": {
"200": {
"window_fixed_arch_low": {
"default": false,
"price": "2"
}
},
"300":{
"window_fixed_arch_regular": {
"default": false,
"price": "3"
}
}
}
}
我只想检索所有具有heights.*.window_fixed_arch_regular
属性的文档。我试过了
({'heights.$.window_fixed_arch_regular', 'exists', true})
但没有运气。
在所有高度(在我的情况下为 200 和 300)中“搜索”而不指定它并检查“window_fixed_arch_low”是否存在的查询是什么?
解决方案
您可以在 3.6 中使用以下查询。
$objectToArray
将heights
文档转换为键值对,然后$filter
将输入值与文档中的值进行比较。
$expr
在查找查询中接受聚合表达式。
$gt > null
- 聚合表达式检查匹配值存在的位置,然后$size
输出计数。
$gt > 0
- 聚合表达式检查计数大于 0 的位置。
db.collectionName.find({
"$expr":{
"$gt":[
{"$size":{
"$filter":{
"input":{"$objectToArray":"$heights"},
"cond":{"$gt":["$$this.v.window_fixed_arch_low",null]}
}
}},
0
]
}
})
推荐阅读
- javascript - 如何重新应用被 ThemeProvider 删除的样式类?
- laravel - Laravel 上的 Predis stream_socket_enable_crypto() 错误
- python - 在Django中以相同的表单方法为两个不同的提交按钮传递值
- verilog - 为什么向上/向下计数器不倒计时?
- git - 将新存储库推送到 Synology git 服务器时出现问题
- reactjs - 反应 JS 组件不显示
- python - Pandas:通过在 MultiIndexed DataFrame 上移动来添加列
- azure - 如何避免通过 terraform 脚本更新应用程序网关的后端池
- swiftui - 如何在我新创建的 SwiftUI 项目中处理这些错误消息?
- go - 获取 GORM 中的递归字段值