Particular field as result in MongoDB?


To get particular field as a result in MongoDB, you can use findOne(). Following is the syntax −

db.yourCollectionName.findOne({"yourFieldName1":yourValue},{yourFieldName2:1});

Let us first create a collection with documents −

> db.particularFieldDemo.insertOne({"EmployeeName":"John Smith","EmployeeAge":26,"EmployeeTechnology":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9b4abb50a6c6dd317ada2")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"Chris Brown","EmployeeAge":28,"EmployeeTechnology":"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9b4d2b50a6c6dd317ada3")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"David Miller","EmployeeAge":30,"EmployeeTechnology":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9b4e8b50a6c6dd317ada4")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"John Doe","EmployeeAge":31,"EmployeeTechnology":"C++"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9b527b50a6c6dd317ada5")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd9b4abb50a6c6dd317ada2"),
   "EmployeeName" : "John Smith",
   "EmployeeAge" : 26,
   "EmployeeTechnology" : "MongoDB"
}
{
   "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"),
   "EmployeeName" : "Chris Brown",
   "EmployeeAge" : 28,
   "EmployeeTechnology" : "Java"
}
{
   "_id" : ObjectId("5cd9b4e8b50a6c6dd317ada4"),
   "EmployeeName" : "David Miller",
   "EmployeeAge" : 30,
   "EmployeeTechnology" : "MySQL"
}
{
   "_id" : ObjectId("5cd9b527b50a6c6dd317ada5"),
   "EmployeeName" : "John Doe",
   "EmployeeAge" : 31,
   "EmployeeTechnology" : "C++"
}

Following is the query to find particular field as result in MongoDB −

> db.particularFieldDemo.findOne({"EmployeeTechnology":"Java"},{EmployeeName:1});

This will produce the following output −

{
   "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"),
   "EmployeeName" : "Chris Brown"
}
raja
Published on 13-Jun-2019 15:03:26
Advertisements