Return a specific field in MongoDB?

MongoDBDatabaseBig Data Analytics

Too return a specific field, use the find() method in MongoDB. Let us first create a collection with documents −

> db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb8019a623186894665ae31")
}
> db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb801ab623186894665ae32")
}
> db.specificFieldDemo.insertOne({"FirstName":"David","LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb801b3623186894665ae33")
}
> db.specificFieldDemo.insertOne({"FirstName":"Sam","LastName":"Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb801bf623186894665ae34")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cb8019a623186894665ae31"),
   "FirstName" : "John",
   "LastName" : "Doe"
}
{
   "_id" : ObjectId("5cb801ab623186894665ae32"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5cb801b3623186894665ae33"),
   "FirstName" : "David",
   "LastName" : "Miller"
}
{
   "_id" : ObjectId("5cb801bf623186894665ae34"),
   "FirstName" : "Sam",
   "LastName" : "Williams"
}

Following is the query to return specific field. Here, we are returning the field “LastName” −

> db.specificFieldDemo.find({},{_id:0,LastName:1});

This will produce the following output −

{ "LastName" : "Doe" }
{ "LastName" : "Smith" }
{ "LastName" : "Miller" }
{ "LastName" : "Williams" }
raja
Published on 30-Apr-2019 08:45:19
Advertisements