【问题标题】:Mongoose - Finding Documents based on the IDs in an ArrayMongoose - 根据数组中的 ID 查找文档
【发布时间】: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'] } }

标签: mongodb express mongoose


【解决方案1】:

您可以使用$in 运算符。

{ _id: { $in: ["mongoID1", "mongoID2", "mongoID3"] } }

如果_id的类型是ObjectId,那么你需要在传递之前将它们转换为ObjectId

{
  _id: {
    $in: [
      mongoose.Types.ObjectId("mongoID1"),
      mongoose.Types.ObjectId("mongoID2"),
      mongoose.Types.ObjectId("mongoID3"),
    ],
  },
}

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 2012-01-08
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多