How to get items with a specific value from documents using MongoDB shell?

MongoDBDatabaseBig Data Analytics

To get items with a specific value, simply use find(). Let us create a collection with documents −

> db.demo563.insertOne({"Name":"Chris","Age":21,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f546c54b4472ed3e8e878")
}
> db.demo563.insertOne({"Name":"Bob","Age":23,"isMarried":false}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f547854b4472ed3e8e879")
}
> db.demo563.insertOne({"Name":"Carol","Age":23,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f548b54b4472ed3e8e87a")
}
> db.demo563.insertOne({"Name":"Mike","Age":21,"isMarried":true}){
   "acknowledged" : true, "insertedId" : ObjectId("5e8f549454b4472ed3e8e87b")
}

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

> db.demo563.find();

This will produce the following output −

{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true }
{ "_id" : ObjectId("5e8f547854b4472ed3e8e879"), "Name" : "Bob", "Age" : 23, "isMarried" : false }
{ "_id" : ObjectId("5e8f548b54b4472ed3e8e87a"), "Name" : "Carol", "Age" : 23, "isMarried" : true }
{ "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }

Following is the query to get items from documents using MongoDB shell

> db.demo563.find({Age:21},{isMarried:true,Name:1,Age:1});

This will produce the following output −

{ "_id" : ObjectId("5e8f546c54b4472ed3e8e878"), "Name" : "Chris", "Age" : 21, "isMarried" : true }
{ "_id" : ObjectId("5e8f549454b4472ed3e8e87b"), "Name" : "Mike", "Age" : 21, "isMarried" : true }
raja
Published on 14-May-2020 08:27:26
Advertisements