mongo 查询 - 属性 是否存在?

mongo query - does property exist?

在集合文档中有一个 'sub' 属性 是一个包含 1 个或多个属性的对象。该集合看起来像:(我删除了无关的其他属性)

"properties": {
    "source": {
        "a/name": 12837,
        "a/different/name": 76129
    }
}

我需要查找 a/name 和 a/different/name 是变量的集合。

这些变量嵌入了前斜杠,因为它们是 mqtt 主题名称,以防您感到疑惑。

(node.js)

我试过:

collection.find({'properties.source[variable containing name]': {$exists: true}}).toArray(function...

不起作用,没有任何返回

我也试过设置查询字符串,如下所示:

var q = util.format('properties.source.%s', variable containing name);
collection.find({q: {$exists: true}}).toArray(function...

因查询错误而失败

如果有问题,我可以用其他字符替换前斜杠,但我怀疑它们没问题。我试过转义前面的斜杠,但没有任何区别。

有什么建议吗?

因为您有 properties 一个对象并且 source 也是一个对象,您应该在如下查询中使用 $exist

db.collection.find({"properties.source.a/name":{$exists:true}})

你不能直接使用一个变量作为对象键,所以你需要把它改成这样:

var name = 'a/name';
var query = {};
query['properties.source.' + name] = {$exists: true};
collection.find(query).toArray(function...