Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo, find through list of ids

Tags:

mongodb

I have a process that returns a list of String MongoDB ids,

[512d5793abb900bf3e20d012, 512d5793abb900bf3e20d011] 

And I want to fire a single query to Mongo and get the matching documents back in the same order as the list.

What is the shell notation to do this?

like image 852
Will Avatar asked Feb 27 '13 01:02

Will


People also ask

How do I search a list in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I search multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

How do I use $in in MongoDB?

Use the $in Operator to Match Values This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15. Although you can write this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


2 Answers

After converting the strings into ObjectIds, you can use the $in operator to get the docs in the list. There isn't any query notation to get the docs back in the order of your list, but see here for some ways to handle that.

var ids = ['512d5793abb900bf3e20d012', '512d5793abb900bf3e20d011']; var obj_ids = ids.map(function(id) { return ObjectId(id); }); db.test.find({_id: {$in: obj_ids}}); 
like image 196
JohnnyHK Avatar answered Oct 15 '22 16:10

JohnnyHK


This works fine for me in Robo 3T. No need to create any object and just use the list of ids.

db.getCollection('my_collection').find({'_id':{$in:['aa37ba96']}}) 
like image 34
Aminah Nuraini Avatar answered Oct 15 '22 17:10

Aminah Nuraini