问题
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