0

I am running into problems deriving the correct MongoDB query. I am trying to formulate a query using the find operation that will retrieve multiple specified ids at once. Note that I cannot use ObjectId() functions. I need to use plain operators like $or, $and, $in, etc.

The dataset in MongoDB has rows that look like the following:

{
 "_id": {
  "$oid": "123"
 },
 "someField": "hello"
 ...
}
{
 "_id": {
  "$oid": "456"
 },
 "someField": "hello"
 ...
}

I have been able to use $or successfully in the following way, but since the MongoDB documentation suggests using $in over $or in terms of performance, I'd like to know how to do this using $in:

{ $or: [{ "_id": {   "$oid": "123"   }  },{ "_id": {   "$oid": "456"}}]}

I have tried the following queries, but none of them have returned any results:

{ "_id":  { $in: ["123", "456"] } }
{ "_id": { $in: [  "$oid": "123","$oid": "456"  ]} } 
{ "_id.$oid":  { $in: ["123", "456"]  }   }

As a last note, I cannot use any queries that completely isolate the object ids, as I am querying for the "someField" field of every matched object id as well.

1 Answer 1

1

You almost had it :

{ "_id": { $in: [  "$oid": "123","$oid": "456"  ]} } 
should read
{ "_id":{ $in:[{"$oid":"123"},{"$oid":"456"}]}} 

You pass in an array but because you are searching the _id field you need to send {"$oid":"oid_value"} for each item

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.