提示信息

mongodb ,根据id 列表查询文档

思韵 已关注

在MongoDB中,如果你想根据一个ID列表查询文档,你可以使用 $in 操作符。以下是一个在 Node.js 中使用 MongoDB 官方驱动的例子:

  1. const MongoClient = require('mongodb').MongoClient;
  2. const ObjectId = require('mongodb').ObjectId;
  3. const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
  4. const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
  5. client.connect(err => {
  6. const collection = client.db("test").collection("documents");
  7. // Assuming we are searching by _id field and ids is an array of string ids
  8. const ids = ['5d378db94e84753160e08b30', '5d378db94e84753160e08b31'];
  9. const objectIdArray = ids.map(id => new ObjectId(id));
  10. collection.find({ _id: { $in: objectIdArray } }).toArray(function(err, docs) {
  11. console.log(docs);
  12. client.close();
  13. });
  14. });

上述示例中,我们首先会创建一个 ObjectId 数组(因为 MongoDB 中默认的 _idObjectId 类型),然后用这个数组作为 $in 操作符的值进行查询。

注意:在链接字符串 mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority 中,请将 <username><password> 替换为你的实际用户名和密码。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
思韵 关注 已关注

最近一次登录:2023-10-09 14:48:46   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图