MongoDB query select and display only a specific field from the 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" }
raja
Published on 14-Jun-2019 15:38:49
Advertisements