Pankaj
Pankaj

Reputation: 1271

How to get multiple document using array of MongoDb id?

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.

How can I search using multiple Ids ?

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

I am able to get records by passing single id like

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

Upvotes: 88

Views: 113787

Answers (7)

klimqx
klimqx

Reputation: 147

The Id's need to be in this format : ObjectId("id").
you can use this to transform your string ID's :

const ObjectId = require('mongodb').ObjectId;

Upvotes: 1

shashigura
shashigura

Reputation: 153

store array list in var and pass that array list to find function var list=db.collection_name.find() db.collection_name.find({_id:{$in:list}})

Upvotes: 0

ishantraj
ishantraj

Reputation: 15

db.getCollection({your_collection_name}).find({
    "_id" : {
    "$in" : 
      [({value1}), 
       ({value2})
      ]
   } 
    })

Upvotes: -4

ifredy3
ifredy3

Reputation: 29

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"]

Upvotes: 1

VIKAS KOHLI
VIKAS KOHLI

Reputation: 8440

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

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

Upvotes: 12

Kane Blueriver
Kane Blueriver

Reputation: 4268

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

You can find more information about ObjectID here.

Just try:

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

Upvotes: 88

Vimalraj Selvam
Vimalraj Selvam

Reputation: 2245

I believe you are missing the ObjectId. Try this:

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

Upvotes: 39

Related Questions