【问题标题】:mongodb/mongoose findMany - find all documents with IDs listed in arraymongodb/mongoose findMany - 查找 ID 列在数组中的所有文档
【发布时间】:2012-01-08 09:18:18
【问题描述】:

我有一个 _ids 数组,我想相应地获取所有文档,最好的方法是什么?

类似...

// doesn't work ... of course ...

model.find({
    '_id' : [
        '4ed3ede8844f0f351100000c',
        '4ed3f117a844e0471100000d', 
        '4ed3f18132f50c491100000e'
    ]
}, function(err, docs){
    console.log(docs);
});

该数组可能包含数百个 _id。

【问题讨论】:

    标签: node.js mongodb mongoose filtering


    【解决方案1】:

    mongoose 中的find 函数是对 mongoDB 的完整查询。这意味着您可以使用方便的 mongoDB $in 子句,其工作方式与 SQL 版本相同。

    model.find({
        '_id': { $in: [
            mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
            mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
            mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
        ]}
    }, function(err, docs){
         console.log(docs);
    });
    

    即使对于包含数万个 id 的数组,这种方法也能很好地工作。 (见Efficiently determine the owner of a record)

    我建议任何使用mongoDB 的人阅读优秀Official mongoDB Docs 的Advanced Queries 部分

    【讨论】:

    • 这个讨论有点晚了,但是您如何确保返回的项目的顺序与您在数组中提供的项目数组的顺序相匹配?除非您指定排序,否则不保证文档以任何顺序出现。如果您希望它们按照您在数组中列出的顺序(例如 ...000c、...000d、...000e)进行排序怎么办?
    • 由于某种原因这不起作用。我有一个空的文档数组
    • @chovy 先尝试converting them to ObjectIds,而不是传递字符串。
    • @Kevin 您可能对此答案感兴趣:stackoverflow.com/a/22800784/133408
    • @Schybo 这完全没有区别。 { _id : 5 } 与 { '_id' : 5 } 相同。
    【解决方案2】:

    node.js 和 MongoChef 都强制我转换为 ObjectId。这就是我用来从数据库中获取用户列表并获取一些属性的方法。注意第 8 行的类型转换。

    // this will complement the list with userName and userPhotoUrl based on userId field in each item
    augmentUserInfo = function(list, callback){
            var userIds = [];
            var users = [];         // shortcut to find them faster afterwards
            for (l in list) {       // first build the search array
                var o = list[l];
                if (o.userId) {
                    userIds.push( new mongoose.Types.ObjectId( o.userId ) );           // for the Mongo query
                    users[o.userId] = o;                                // to find the user quickly afterwards
                }
            }
            db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
                if (err) callback( err, list);
                else {
                    if (user && user._id) {
                        users[user._id].userName = user.fName;
                        users[user._id].userPhotoUrl = user.userPhotoUrl;
                    } else {                        // end of list
                        callback( null, list );
                    }
                }
            });
        }
    

    【讨论】:

    • userIds = _.map(list, function(userId){ return mongoose.Types.ObjectId(userId) };
    • 我不必使用 mongoose 4.5.9 转换为 ObjectID。
    【解决方案3】:

    使用这种查询格式

    let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));
    
    Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
      .where('category')
      .in(arr)
      .exec();
    

    【讨论】:

      【解决方案4】:

      Ids 是对象 id 的数组:

      const ids =  [
          '4ed3ede8844f0f351100000c',
          '4ed3f117a844e0471100000d', 
          '4ed3f18132f50c491100000e',
      ];
      

      在回调中使用 Mongoose:

      Model.find().where('_id').in(ids).exec((err, records) => {});
      

      使用带有异步功能的 Mongoose:

      const records = await Model.find().where('_id').in(ids).exec();
      

      或者更简洁:

      const records = await Model.find({ '_id': { $in: ids } });
      

      不要忘记用您的实际模型更改模型。

      【讨论】:

      • 这应该是公认的答案,因为它是最新且连贯的答案。您不必像接受的答案那样将 id 转换为 ObjectId,它使用 mongoose 命令式样式查询。谢谢顺便说一句!
      • 这是一个非常干净和更新的方法,如果你不介意我想问几个问题,如果我有一组引用的ObjectId,就像上面一样(比如,我有项目,并且我用用户模型上引用的 project_id 为某些用户分配了一个项目数组),如果我删除一个项目,我如何确保从用户模型引用的数组中删除 id ?谢谢垫子。
      • 这就是我需要的!它干净且易于使用在另一个模型中作为参考的 id
      • 这很好用!对于优化版本,您可以在末尾附加 .lean() ,它将仅返回 POJO(普通旧 Javascript 对象)。您还可以添加 select() 并仅选择文档的必填字段。
      【解决方案5】:

      结合丹尼尔和 snnsnn 的答案:

      let ids = ['id1','id2','id3']
      let data = await MyModel.find(
        {'_id': { $in: ids}}
      );

      简单而干净的代码。它的工作原理和测试:

      "mongodb": "^3.6.0", "猫鼬": "^5.10.0",

      【讨论】:

      • 我一直将 id 放在数组括号 [] 中,但从您的回答中意识到它已经是一个数组:|
      • @RizaKhan 非常感谢!我犯了同样的错误。
      【解决方案6】:

      从 mongoDB v4.2 和 mongoose 5.9.9 开始,这段代码对我很有效:

      const Ids = ['id1','id2','id3']
      const results = await Model.find({ _id: Ids})
      

      ID 可以是ObjectId 或String 类型

      【讨论】:

        【解决方案7】:

        我尝试了下面的方法,它对我有用。

        var array_ids=['1','2','6','9'] // your array of ids
        model.find({ '_id': { $in: array_ids }}).toArray(function(err, data) {
                    if (err) {
                        logger.winston.error(err);
                    } else {
                        console.log("data", data);
                    }
                });
        

        【讨论】:

          【解决方案8】:

          如果你使用的是 async-await 语法,你可以使用

          const allPerformanceIds = ["id1", "id2", "id3"];
          const findPerformances = await Performance.find({ _id: { $in: allPerformanceIds } });
                     
          

          【讨论】:

            【解决方案9】:

            我正在使用此查询在 mongo GridFs 中查找文件。我想通过它的 ID 来获取。

            对我来说,这个解决方案有效:Ids type of ObjectId。

            gfs.files
            .find({ _id: mongoose.Types.ObjectId('618d1c8176b8df2f99f23ccb') })
            .toArray((err, files) => {
              if (!files || files.length === 0) {
                return res.json('no file exist');
              }
              return res.json(files);
              next();
            });
            

            这不起作用:Id type of string

            gfs.files
            .find({ _id: '618d1c8176b8df2f99f23ccb' })
            .toArray((err, files) => {
              if (!files || files.length === 0) {
                return res.json('no file exist');
              }
              return res.json(files);
              next();
            });
            

            【讨论】:

              猜你喜欢
              • 2021-11-04
              • 2021-01-13
              • 1970-01-01
              • 2021-06-06
              • 2016-03-21
              • 1970-01-01
              • 2020-05-17
              • 2022-01-17
              相关资源
              最近更新 更多