mongodb/mongoose findMany - 查找在数组中列出ID的所有文档

ezm*_*use 218 mongoose mongodb node.js

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

就像是 ...

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

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

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

Dan*_*del 430

findmongoose中的函数是对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);
});
Run Code Online (Sandbox Code Playgroud)

即使对于包含数万个ID的数组,此方法也能正常工作.(请参阅有效确定记录的所有者)

我建议任何人mongoDB阅读优秀的官方mongoDB文档高级查询部分

  • 有点迟到这个讨论,但是你如何确保返回的项目的顺序与你在数组中提供的项目数组的顺序相匹配?除非您指定排序,否则不保证文档以任何顺序出现.如果您希望它们按照您在阵列中列出的顺序排序(例如... 000c,... 000d,... 000e),该怎么办? (8认同)
  • 由于某种原因,这不起作用.我得到了一个空数组的文档 (7认同)
  • @chovy首先尝试[将它们转换为ObjectIds](/sf/ask/460472491/),而不是传递字符串. (2认同)
  • @Kevin 你可能对这个答案感兴趣:http://stackoverflow.com/a/22800784/133408 (2认同)
  • @Schybo 这绝对没有区别。`{ _id : 5 }` 与 `{ '_id' : 5 }` 相同。 (2认同)

snn*_*snn 101

Ids 是对象 ID 的数组:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];
Run Code Online (Sandbox Code Playgroud)

使用带有回调的猫鼬:

Model.find().where('_id').in(ids).exec((err, records) => {});
Run Code Online (Sandbox Code Playgroud)

使用具有异步功能的猫鼬:

const records = await Model.find().where('_id').in(ids).exec();
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

const records = await Model.find({ '_id': { $in: ids } });
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是公认的答案,因为它是最新且连贯的答案。您不必像接受的答案一样将 ids 转换为 ObjectId,并且它使用 *mongoose* 命令式查询。谢谢顺便说一句! (3认同)

Ahm*_*yah 14

结合 Daniel 和 snnsnn 的回答:

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

简单干净的代码。它适用于并测试:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",


小智 8

使用此格式的查询

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();
Run Code Online (Sandbox Code Playgroud)


MD *_*YON 7

如果您使用 async-await 语法,您可以使用

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


Nic*_*ico 5

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 );
                }
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

  • userIds = _.map(list, function(userId){ return mongoose.Types.ObjectId(userId) }; (7认同)

faf*_*nzm 5

从 mongoDB v4.2 和 mongoose 5.9.9 开始,这段代码对我来说很好用:

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

并且 Id 可以是类型ObjectIdString