mongodb Mongo,通过 id 列表查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15102532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:04:39  来源:igfitidea点击:

Mongo, find through list of ids

mongodb

提问by Will

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

我有一个返回字符串 MongoDB id 列表的进程,

[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.

我想向 Mongo 发出一个查询,并按照与列表相同的顺序取回匹配的文档。

What is the shell notation to do this?

执行此操作的 shell 符号是什么?

回答by JohnnyHK

After converting the strings into ObjectIds, you can use the $inoperator 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 herefor some ways to handle that.

将字符串转换为 ObjectIds 后,您可以使用$in运算符获取列表中的文档。没有任何查询符号可以按照列表的顺序返回文档,但请参阅此处了解处理该问题的一些方法。

var ids = ['512d5793abb900bf3e20d012', '512d5793abb900bf3e20d011'];
var obj_ids = ids.map(function(id) { return ObjectId(id); });
db.test.find({_id: {$in: obj_ids}});

回答by jianpx

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.

如果你的最终目的是通过你的pre-get ids list获取有顺序的文档,你可以直接将查询结果转换成mapping(id as key, doc as value),然后遍历ids列表来获取文档。

回答by Sudhir Kushwaha

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

// 请求中的 categoryId 逗号分隔“5c875c27d131b755d7abed86,5c875b0ad131b755d7abed81”

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

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