81

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?

Ry-
  • 209,133
  • 54
  • 439
  • 449
Will
  • 5,955
  • 4
  • 29
  • 48

4 Answers4

133

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}});
Asclepius
  • 49,954
  • 14
  • 144
  • 128
JohnnyHK
  • 290,447
  • 61
  • 595
  • 453
  • This is working perfectly but i have an other query where i want only one record for the list of ids what should i do for that ? – Shashank Dubey Dec 24 '20 at 10:18
  • how can i get ids in an array from this : { "_id" : ObjectId("611b96a6699005a8f561fe52") }, { "_id" : ObjectId("611b96a2699005a8f561fe51") } – Youssef Boudaya Aug 17 '21 at 22:12
5

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']}})
Aminah Nuraini
  • 16,240
  • 7
  • 82
  • 100
1

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

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

db.test.find({ categoryId: { $in: ids } });
  • Does not answer the question. The question clearly shows an **array** and not a string. If you had something else to add on a **different** note, you could have [asked a new question](https://stackoverflow.com/questions/ask) and posted your own response. Adding *unrelated* answers to existing questions is not necessary. – Neil Lunn Oct 02 '19 at 09:49
0

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.

jianpx
  • 3,112
  • 1
  • 29
  • 26
  • 1
    I'm after the query that will return the results...? Code example would be much appreciated. – Will Feb 27 '13 at 03:39