Selecting only a single field from MongoDB?


You can use $and operator. Let us first create a collection with documents −

>db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd547142cba06f46efe9f02")
}
>db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"Carol","StudentAge":21,"StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd5471f2cba06f46efe9f03")
}
>db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"David","StudentAge":24,"StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd5472c2cba06f46efe9f04")
}
>db.selectingASingleFieldDemo.insertOne({"StudentFirstName":"Robert","StudentAge":26,"StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd548382cba06f46efe9f05")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd547142cba06f46efe9f02"),
   "StudentFirstName" : "John",
   "StudentAge" : 23,
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5cd5471f2cba06f46efe9f03"),
   "StudentFirstName" : "Carol",
   "StudentAge" : 21,
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5cd5472c2cba06f46efe9f04"),
   "StudentFirstName" : "David",
   "StudentAge" : 24,
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5cd548382cba06f46efe9f05"),
   "StudentFirstName" : "Robert",
   "StudentAge" : 26,
   "StudentCountryName" : "AUS"
}

Following is the query to select only a single field from MongoDB −

> db.selectingASingleFieldDemo.find(
... { $and:[{StudentAge: { $gt:21 } },
... {"StudentCountryName" : "AUS"}] },
... {StudentFirstName: 1, _id: 0});

This will produce the following output −

{ "StudentFirstName" : "David" }
{ "StudentFirstName" : "Robert" }

Updated on: 30-Jul-2019

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements