Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Fetch specific field values in MongoDB
To fetch specific field values in MongoDB, use the $in operator to match documents where a field value equals any value in a specified array, combined with projection to return only the desired fields.
Syntax
db.collection.find(
{ fieldName: { $in: ["value1", "value2", "value3"] } },
{ field1: 1, field2: 0, _id: 0 }
);
Sample Data
Let us create a collection with student documents ?
db.indexesDemo.insertMany([
{"StudentFirstName": "John", "StudentLastName": "Smith"},
{"StudentFirstName": "Chris", "StudentLastName": "Brown"},
{"StudentFirstName": "John", "StudentLastName": "Doe"},
{"StudentFirstName": "David", "StudentLastName": "Miller"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e06de4d25ddae1f53b621dd"),
ObjectId("5e06de5825ddae1f53b621de"),
ObjectId("5e06de6725ddae1f53b621df"),
ObjectId("5e06de7225ddae1f53b621e0")
]
}
View All Documents
db.indexesDemo.find();
{ "_id": ObjectId("5e06de4d25ddae1f53b621dd"), "StudentFirstName": "John", "StudentLastName": "Smith" }
{ "_id": ObjectId("5e06de5825ddae1f53b621de"), "StudentFirstName": "Chris", "StudentLastName": "Brown" }
{ "_id": ObjectId("5e06de6725ddae1f53b621df"), "StudentFirstName": "John", "StudentLastName": "Doe" }
{ "_id": ObjectId("5e06de7225ddae1f53b621e0"), "StudentFirstName": "David", "StudentLastName": "Miller" }
Example: Fetch Specific Field Values
Find documents where StudentFirstName is either "John" or "David", returning only the StudentFirstName field ?
db.indexesDemo.find(
{ StudentFirstName: { $in: ["John", "David"] } },
{ _id: 0, StudentLastName: 0 }
);
{ "StudentFirstName": "John" }
{ "StudentFirstName": "John" }
{ "StudentFirstName": "David" }
Key Points
-
$inoperator matches documents where the field value equals any value in the array. - Use projection (
{ field: 0 }) to exclude unwanted fields from results. - Set
_id: 0to exclude the default ObjectId field.
Conclusion
The $in operator combined with field projection allows you to efficiently fetch specific field values that match multiple criteria. This approach is useful for filtering and retrieving targeted data from MongoDB collections.
Advertisements
