Mongo, find through list of ids

2019-01-11 12:13发布

问题:

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?

回答1:

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


回答2:

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.



标签: mongodb