首页 > 解决方案 > 如何检查 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}}}])

我需要这个例子的帮助和很多解释。

标签: mongodbnestedkeyaggregation

解决方案


您不需要检查某个字段是否存在,只要您需要检查该字段是否为真,只需添加'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 对象


推荐阅读