mongo query - does property exist?

巧了我就是萌 提交于 2020-01-06 03:32:06

问题


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
    }
}

I need to do a find on the collection where a/name and a/different/name are variables.

The variables have embedded front slashes because they are mqtt topic names, in case you wonder.

(node.js)

I've tried:

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...

Fails with query error

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.

Any suggestions?


回答1:


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...



回答2:


As you have properties an object and source is also an object, You should use $exist in a query like following :

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


来源:https://stackoverflow.com/questions/30302513/mongo-query-does-property-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!