You can select a single field in MongoDB using the following syntax:
db.yourCollectionName.find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
In the above syntax "yourSingleFieldName":1, _id:0 means get all data from one field without _id.
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
> db.singleFieldDemo.insertOne({"StudentName":"David","StudentAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5c6eba356fd07954a489067c") } > db.singleFieldDemo.insertOne({"StudentName":"Bob","StudentAge":18}); { "acknowledged" : true, "insertedId" : ObjectId("5c6eba406fd07954a489067d") } > db.singleFieldDemo.insertOne({"StudentName":"Chris","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c6eba4c6fd07954a489067e") } > db.singleFieldDemo.insertOne({"StudentName":"Robert","StudentAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c6eba586fd07954a489067f") }
Now you can display all documents from a collection with the help of find() method. The query is as follows:
> db.singleFieldDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6eba356fd07954a489067c"), "StudentName" : "David", "StudentAge" : 28 } { "_id" : ObjectId("5c6eba406fd07954a489067d"), "StudentName" : "Bob", "StudentAge" : 18 } { "_id" : ObjectId("5c6eba4c6fd07954a489067e"), "StudentName" : "Chris", "StudentAge" : 24 } { "_id" : ObjectId("5c6eba586fd07954a489067f"), "StudentName" : "Robert", "StudentAge" : 26 }
Here is the query to select a single field:
> db.singleFieldDemo.find({"StudentAge":18},{"StudentName":1,"_id":0});
The following is the output:
{ "StudentName" : "Bob" }