Matching MongoDB collection items by id?

MongoDBDatabaseBig Data Analytics

To match collection items by id, use $in in MongoDB. Let us create a collection with documents −

> db.demo528.insertOne({"Name":"Chris",Age:21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b00d2ef4dcbee04fbbbe0")
}
> db.demo528.insertOne({"Name":"Bob",Age:22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b00d9ef4dcbee04fbbbe1")
}
> db.demo528.insertOne({"Name":"David",Age:20});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b00e0ef4dcbee04fbbbe2")
}

Display all documents from a collection with the help of find() method −

> db.demo528.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e8b00d9ef4dcbee04fbbbe1"), "Name" : "Bob", "Age" : 22 }
{ "_id" : ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name" : "David", "Age" : 20 }

Following is the query to match collection item by id −

> db.demo528.find({
   _id: {$in:[ObjectId("5e8b00d2ef4dcbee04fbbbe0"),ObjectId("5e8b00e0ef4dcbee04fbbbe2")]}
});

This will produce the following output −

{ "_id" : ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name" : "David", "Age" : 20 }
raja
Published on 13-May-2020 07:37:56
Advertisements