如何使用 MongoDb id 数组获取多个文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32264225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:31:47  来源:igfitidea点击:

How to get multiple document using array of MongoDb id?

mongodb

提问by Pankaj

I have an array of ids and I want to get all document of them at once. For that I am writing but it return 0 records.

我有一组 id,我想一次获取它们的所有文档。为此,我正在写作,但它返回 0 条记录。

How can I search using multiple Ids ?

如何使用多个 Id 进行搜索?

db.getCollection('feed').find({"_id" : { "$in" : [  
"55880c251df42d0466919268","55bf528e69b70ae79be35006" ]}})

I am able to get records by passing single id like

我可以通过传递单个 id 来获取记录

db.getCollection('feed').find({"_id":ObjectId("55880c251df42d0466919268")})

回答by kxxoling

MongoDB is type sensitive, which means 1is different with '1', so are "55880c251df42d0466919268"and ObjectId("55880c251df42d0466919268"). The later one is in ObjectID type but not str, and also is the default _idtype of MongoDB document.

MongoDB 是类型敏感的,这意味着1与 不同'1'"55880c251df42d0466919268"和 也是ObjectId("55880c251df42d0466919268")。后者是ObjectID类型而不是str,也是_idMongoDB文档的默认类型。

You can find more information about ObjectID here.

您可以在此处找到有关 ObjectID 的更多信息。

Just try:

你试一试:

db.getCollection('feed').find({"_id" : {"$in" : [ObjectId("55880c251df42d0466919268"), ObjectId("55bf528e69b70ae79be35006")]}});

回答by Vimalraj Selvam

I believe you are missing the ObjectId. Try this:

我相信你错过了ObjectId. 尝试这个:

db.feed.find({ 
    _id: {
        $in: [ObjectId("55880c251df42d0466919268"), ObjectId("55bf528e69b70ae79be35006")]
    }
});

回答by VIKAS KOHLI

For finding records of multiple documents you have to use "$in" operator Although your query is fine, you just need to add ObjectId while finding data for Ids

要查找多个文档的记录,您必须使用“$in”运算符虽然您的查询很好,但您只需要在查找 Id 数据时添加 ObjectId

db.feed.find({
  "_id" : {
    "$in" : 
      [ObjectId("55880c251df42d0466919268"), 
       ObjectId("55bf528e69b70ae79be35006")
      ]
   }
});

回答by ifredy3

Just I have use it, and is working fine:

只是我使用过它,并且工作正常:

module.exports.obtenerIncidencias386RangoDias = function (empresas, callback) {
    let arraySuc_Ids = empresas.map((empresa)=>empresa.sucursal_id)
            incidenciasModel.find({'sucursal_id':{$in:arraySuc_Ids}
            }).sort({created_at: 'desc'}).then(
                (resp)=>    {
                    callback(resp)}
            )
};

where:

在哪里:

empresas = ["5ccc642f9e789820146e9cb0","5ccc642f9e789820146e9bb9"]

empresas = ["5ccc642f9e789820146e9cb0","5ccc642f9e789820146e9bb9"]