mongo查询 – 属性是否存在?

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

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

我需要在集合中find/ name和/ different / name是variables。

variablesembedded正斜线,因为它们是mqtt主题名称,以防万一您想知道。

(的node.js)

我试过了:

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

不工作,没有任何返回

我也试着设置一个查询string,如下所示:

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

查询错误失败

如果他们是问题,我可以用其他字符replace前斜线,但是我怀疑他们没问题。 我试图逃脱前斜线,这没有什么区别。

有什么build议么?

您不能直接使用variables作为对象键,所以您需要将其更改为如下所示:

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

因为你有properties一个对象和source也是一个对象,你应该使用$存在一个查询如下:

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