1

While building an API, I need to match documents that contain pending or active values for the key status.

When trying

args.status = {
  $or: [
    'active',
    'pending'
  ]
}

I get an error: cannot use $or with string

However,

args.status = {
  $in: [
    'active',
    'pending'
  ]
}

works just fine.

I would expect $or to work here. Can someone provide context on the differences between the two and why Strings require $in?

joe
  • 53
  • 6

2 Answers2

0

Thats because $or expects array of objects. Objects that defines some filters out of which at least one needs to be match to return the result. For your particular scenario $in is the best option. Still if you wanna go with $or, the query will be like:

{
  $or: [
    {'args.status' : {$eq: 'active'}},
    {'args.status' : {$eq: 'pending'}}
  ]
}

I'd suggest you stick with $in as it is the best fit for your requirement.

You can check the official docs for more details on $or

Hope this helps :)

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26
0

$or performs the logical OR operation on an ARRAY with more than two expressions e.g. {$or:[{name:"a"},{name:"b"}]} This query will return the record which are having either name 'a' or 'b'.

$in works on the array and return the documents which are which contains any of the field from your specified array e.g.{name:{$in:['a','b']}} This query will return the documents where name is either 'a' or 'b'.

Ideally both are doing same but just having the syntax difference.

In your case you have to modify your OR query syntax and add the condition expessions in an ARRAY.

{ $or: [
    {
      "args.status": "active"
    },
    {
      "args.status": "pending"
    }
  ]
}
  • Thanks for your response! Is there one that's more efficient with the example I provided? – joe Aug 08 '19 at 13:40
  • For more details you can refer https://stackoverflow.com/questions/14736656/optimized-way-of-querying-in-mongodb-using-in-vs-or link. – Mayuri S Kulkarni Aug 09 '19 at 09:17