H0miet
H0miet

Reputation: 91

Can't get $or statement to work in nodejs and mongodb

In nodejs I'm trying to run an $or statement to retrieve objects from mongo that could have certain IDs. I use a for loop to push the ids into a string. My code looks like this after the loop.

var filter =  "{ $or: [{'id':1290383},{'id':1290381},{'id':1290382}]}"

const results = await collection.find(filter).toArray();

When I run this it returns everything in the collection. I'm assuming I need to JSON parse it beforehand but I get an error about the $ when I try to parse it. I can't find any information about the correct way to use $or in nodejs. I feel like there should be another way to query different IDs. If someone knows, please let me know.

Upvotes: 0

Views: 66

Answers (1)

R2D2
R2D2

Reputation: 10717

You need to convert the filter variable from string to json object as follow:

 var filter =  '{ "$or": [{"id":1290383},{"id":1290381},{"id":1290382}]}'
 var filterobj = JSON.parse(filter);
 const results = await collection.find(filterobj).toArray();

Also JSON.parse() does not allow single quotes so you will need to enquote the full string with single quotes and the keys with the double quotes.

You could also replace the $or operation with $in operation for the same task (since it is generally easier to read and pretend to be more effective) as follow:

 var filter =  '{ "id":{"$in": [1290383,1290381,1290382] } }'

example from mongo shell:

 mongos> var filter =  '{ "id":{"$in": [1290383,1290381,1290382] } }'
 mongos> var filterobj = JSON.parse(filter); 
 mongos> filterobj
 { "id" : { "$in" : [ 1290383, 1290381, 1290382 ] } }
 mongos> 

Upvotes: 2

Related Questions