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

To display only the employee names with specific salaries in MongoDB, use the $in operator to match multiple salary values and apply field projection to return only the employee names.

Syntax

db.collection.find(
    { "fieldName": { $in: [value1, value2, value3] } },
    { _id: 0, "fieldToExclude": 0 }
);

Sample Data

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

View Sample Data

db.demo666.find();
{ "_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 }

Example: Filter by Specific Salaries

Find employees with salaries of 35000 or 40000 and display only their names ?

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

How It Works

  • $in: [35000, 40000] − Matches documents where EmployeeSalary equals any value in the array
  • _id: 0 − Excludes the default _id field from results
  • "EmployeeSalary": 0 − Excludes the salary field, showing only employee names

Conclusion

Use $in operator with field projection to filter documents by multiple specific values and display only the required fields. This approach efficiently retrieves employee names matching specific salary criteria.

Updated on: 2026-03-15T03:27:10+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements