Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple document using array of MongoDb id?

Tags:

mongodb

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")}) 
like image 981
Pankaj Avatar asked Aug 28 '15 05:08

Pankaj


People also ask

How can I find the value of an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How get all items from MongoDB?

To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.

How do I pop an array in MongoDB?

The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array. The $pop operator has the form: { $pop: { <field>: <-1 | 1>, ... } }


1 Answers

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")]}}); 
like image 188
Kane Blueriver Avatar answered Oct 24 '22 20:10

Kane Blueriver