mongodb - 如何检查 MongoDB 对象中是否存在嵌套键?
问题描述
所以问题是我必须通过使用MongoDB 中的“聚合”函数和“组”运算符来找到每个州的酒店数量。酒店必须至少有 4.5 星,并且属性“Wi-Fi”的值为 true。我在链接下方附加了带有对象结构的图像(来自 Robo3T 的屏幕)
“属性”是业务集合的键,它可以有嵌套键,如“Wi-Fi”,但不是必需的。我不知道如何检查此密钥的存在以及真实值。我写了一些代码但没有检查它(见下文)。
db.business.aggregate([
{$match: {"categories": {$in: ["Hotels"]}, "stars":{$gte: 3.5}}},
{$group: {_id:"$state", count:{$sum:1}}}])
我需要这个例子的帮助和很多解释。
解决方案
您不需要检查某个字段是否存在,只要您需要检查该字段是否为真,只需添加'attributes.Wi-Fi': true
到匹配对象
所以查询应该是
'attributes.Wi-Fi': true
如果您需要检查诸如 Wi-Fi 之类的某些属性是否不存在或等于 false,那么查询应该类似于
1-
'attributes.Wi-Fi': { $ne: true } // wi-fi attribute is not equal to true, this means either wi-fi does not exist or exists but equals any value but not true
2- 或使用 $or 运算符
$or: [
{
'attributes.Wi-Fi': { $exists: false } // wifi attribute does not exist
},
{
'attributes.Wi-Fi': false // or exists and equal to false
}
]
如果需要,只需将任何这些查询添加到 $match 对象
推荐阅读
- sails.js - 如何从 Sails 控制台呼叫助手?
- html - 如何在条件语句中使用 ngClass
- vim - 如何使用 Vim 中的 ./ 相对路径将本地存储的备份目录和交换目录设置为工作目录?
- node.js - 在节点 JS 中解析 Json 数据
- python - AttributeError:“用户”对象没有属性“获取”-带有 PyMongo 的 Flask-Login 用户类
- python - 如何从 Modbus Slave 读取所有保持寄存器?
- postgresql - PostgreSQL UPDATE ON CONFLICT 仅在某些情况下
- c# - 元素的值不会改变
- c# - 如何存储重复 XML 结构的值
- geoserver - Geoserver 无法为 geotiff 创建阅读器