mongo查询-属性是否存在? [英] mongo query - does property exist?
问题描述
在收集文档中,有一个子"属性,该属性是包含1个或多个属性的对象.该集合看起来像:(我已经删除了其他多余的属性)
Within a collection document there is a 'sub' property that is an object containing 1 or more properties. The collection looks like: (I've removes extraneous other properties)
"properties": {
"source": {
"a/name": 12837,
"a/different/name": 76129
}
}
我需要在集合中进行查找,其中a/name和a/different/name是变量.
I need to do a find on the collection where a/name and a/different/name are variables.
如果您想知道的话,这些变量带有斜杠,因为它们是mqtt主题名称.
The variables have embedded front slashes because they are mqtt topic names, in case you wonder.
(node.js)
我尝试过:
collection.find({'properties.source[variable containing name]': {$exists: true}}).toArray(function...
不起作用,什么也没返回
Doesn't work, nothing returned
我也尝试过设置查询字符串,如下所示:
I've also tried setting a query string as in:
var q = util.format('properties.source.%s', variable containing name);
collection.find({q: {$exists: true}}).toArray(function...
失败,出现查询错误
如果有问题,我可以用其他字符替换前斜杠,但我怀疑它们还可以.我已经尝试过转义前斜杠,但这没什么区别.
I could replace the front slashes with some other character if they are the problem but I suspect they are ok. I have tried escaping the front slashes and it makes no difference.
有什么建议吗?
推荐答案
您不能直接将变量用作对象键,因此需要将其更改为以下内容:
You can't directly use a variable as an object key, so you need to change it to something like:
var name = 'a/name';
var query = {};
query['properties.source.' + name] = {$exists: true};
collection.find(query).toArray(function...
这篇关于mongo查询-属性是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!