Syntax error Display only the employee names with specific salaries in MongoDB documents with employee records?

Display only the employee names with specific salaries in MongoDB documents with employee records?



To display only the employee names with specific salaries, set the salaries in MongoDB $in and fetch the names. Let us create a collection with documents

> db.demo666.insertOne({"EmployeeName":"John","EmployeeSalary":25000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1c04824113ea5458c7d0d")
}
> db.demo666.insertOne({"EmployeeName":"Chris","EmployeeSalary":35000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1c05524113ea5458c7d0e")
}
> db.demo666.insertOne({"EmployeeName":"David","EmployeeSalary":65000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1c06024113ea5458c7d0f")
}
> db.demo666.insertOne({"EmployeeName":"Carol","EmployeeSalary":40000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1c06f24113ea5458c7d10")
}

Display all documents from a collection with the help of find() method −

> db.demo666.find();

This will produce the following output −

{ "_id" : ObjectId("5ea1c04824113ea5458c7d0d"), "EmployeeName" : "John", "EmployeeSalary" : 25000 }
{ "_id" : ObjectId("5ea1c05524113ea5458c7d0e"), "EmployeeName" : "Chris", "EmployeeSalary" : 35000 }
{ "_id" : ObjectId("5ea1c06024113ea5458c7d0f"), "EmployeeName" : "David", "EmployeeSalary" : 65000 }
{ "_id" : ObjectId("5ea1c06f24113ea5458c7d10"), "EmployeeName" : "Carol", "EmployeeSalary" : 40000 }

Following is the query to use $in and fetch the employee names with specific salaries −

> db.demo666.find({"EmployeeSalary":{$in:[35000,40000]}},{_id:0,"EmployeeSalary":0});

This will produce the following output −

{ "EmployeeName" : "Chris" }
{ "EmployeeName" : "Carol" }
Updated on: 2020-05-13T09:43:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements