// wrong output
// out -> 0
tags1 = ["key1", "key2"]
tags1.forEach(function(entry) {
var query = {entry : {$exists: true}};
print(entry + " -> " + database.keys.find(query).count());
})
// working fine
// out -> 1
var query = {"key1" : {$exists: true}};
print(database.keys.find(query).count())
Hi
This is because the query was not constructed like you think it is.
You can observe this if you print the query
variable:
> tags1 = ["key1", "key2"
]
[ "key1", "key2" ]
> tags1.forEach(function(entry) {
... var query = {entry : {$exists: true}};
... printjson(query);
... })
{ "entry" : { "$exists" : true } }
{ "entry" : { "$exists" : true } }
To create a JSON document using a variable as the key, you would need to use a bracket notation, e.g.:
> tags1.forEach(function(entry) {
... var query = {}
... query[entry] = {'$exists': true}
... printjson(query);
... })
{ "key1" : { "$exists" : true } }
{ "key2" : { "$exists" : true } }
>
Best regards
Kevin