Select and Display Specific Field from MongoDB Document



Let us first create a collection with documents −

> db.querySelectDemo.insertOne({UserId:100,UserName:"Chris",UserAge:25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90eb478f00858fb12e90e")
}
> db.querySelectDemo.insertOne({UserId:101,UserName:"Robert",UserAge:26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90ec578f00858fb12e90f")
}
> db.querySelectDemo.insertOne({UserId:103,UserName:"David",UserAge:27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce90ed478f00858fb12e910")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.querySelectDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ce90eb478f00858fb12e90e"),
   "UserId" : 100,
   "UserName" : "Chris",
   "UserAge" : 25
}
{
   "_id" : ObjectId("5ce90ec578f00858fb12e90f"),
   "UserId" : 101,
   "UserName" : "Robert",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5ce90ed478f00858fb12e910"),
   "UserId" : 103,
   "UserName" : "David",
   "UserAge" : 27
}

Following is the query to include only a specific field by setting it to TRUE in find() −

> db.querySelectDemo.find({},{_id:0,UserName:true});

This will produce the following output −

{ "UserName" : "Chris" }
{ "UserName" : "Robert" }
{ "UserName" : "David" }
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements