Mongo, find through list of ids

Mongodb

Mongodb Problem Overview


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?

Mongodb Solutions


Solution 1 - Mongodb

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}});

Solution 2 - Mongodb

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']}})

Solution 3 - Mongodb

// categoryId comma separated "5c875c27d131b755d7abed86,5c875b0ad131b755d7abed81" in request

var ids= req.body.categoryId.split(','); 

db.test.find({ categoryId: { $in: ids } });

Solution 4 - Mongodb

If your final purpose is to get the document with the order by your pre-get ids list, you can just convert the query result into mapping(id as key, doc as value) , and then traverse the ids list to get the doc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillView Question on Stackoverflow
Solution 1 - MongodbJohnnyHKView Answer on Stackoverflow
Solution 2 - MongodbAminah NurainiView Answer on Stackoverflow
Solution 3 - MongodbSudhir KushwahaView Answer on Stackoverflow
Solution 4 - MongodbjianpxView Answer on Stackoverflow