executing search query on mongo using javascript

11 views
Skip to first unread message

Swayam Raina

unread,
May 24, 2018, 6:42:22 PM5/24/18
to mongodb-user
Hi,

I am executing a javacript file (contents below) on mongo. But somehow, the function is not executing as expected.

// 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())


as per my understanding the entry variable is not getting passed as a string.

Can anyone please analyse and tell what the exact problem is? or how the method should be updated for corredct output.

Thanks in advance!!

Kevin Adistambha

unread,
May 27, 2018, 8:13:51 PM5/27/18
to mongodb-user

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

Reply all
Reply to author
Forward
0 new messages