【发布时间】:2021-01-13 07:40:42
【问题描述】:
我有一个这样的 mongoID 数组
arrayOfIDs = ['mongoID1','mongoID2','mongoID3']
这些是我收藏中文档的 mongo-id。
现在通过获取这些 mongoID 的数组,即 ['mongoID1','mongoID2','mongoID3'],我需要使用其 _id 查询这些 id 指定的每个文档并处理其数据在我的代码逻辑中独立。 为了简单起见,我只是“打印”了输出,即 res.json(doc.name)。
如果Mongoose/MongoDB中确实存在的话,我需要下面这样的东西
Shop.find({'_id':['mongoID1','mongoID2','mongoID3']})
.exec()
.then(doc =>{
res.json(doc.name)
})
我知道我可以在这种情况下使用循环,就像这样,
for(id of arrayOfIDs){
Shop.find({'_id': id})
.exec()
.then(doc =>{
res.json(doc.name)
})
}
但这涉及根据 arrayOfIDs 的长度多次查询数据库,这是我不想要的。我想要一个本机 mongodb 解决方案,它只在 mongodb 查询中传递 Id,就像我上面的示例一样。
你能告诉我这是如何实现的吗?
【问题讨论】:
-
像这样使用
$in{'_id': { $in: ['mongoID1','mongoID2','mongoID3'] } }