MongoDB query for a single field


For a single field, use find(). Let us first create a collection with documents −

> db.demo10.insertOne({"StudentId":101,"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f68a7d7df943a7cec4f9b")
}
> db.demo10.insertOne({"StudentId":102,"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f68afd7df943a7cec4f9c")
}
> db.demo10.insertOne({"StudentId":103,"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f68b5d7df943a7cec4f9d")
}

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

> db.demo10.find();

This will produce the following output −

{ "_id" : ObjectId("5e0f68a7d7df943a7cec4f9b"), "StudentId" : 101, "StudentName" : "Chris" }
{ "_id" : ObjectId("5e0f68afd7df943a7cec4f9c"), "StudentId" : 102, "StudentName" : "David" }
{ "_id" : ObjectId("5e0f68b5d7df943a7cec4f9d"), "StudentId" : 103, "StudentName" : "Bob" }

Here is the query for a single field −

> db.demo10.find({},{"_id":0,"StudentId":0});

This will produce the following output −

{ "StudentName" : "Chris" }
{ "StudentName" : "David" }
{ "StudentName" : "Bob" }

Updated on: 01-Apr-2020

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements