Fetch specific field values in MongoDB


To fetch specific field values, use $in operator. The $in selects the documents where the value of a field equals any value in the specified array.

Let us first create a collection with documents −

> db.indexesDemo.createIndex({"StudentFirstName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de4d25ddae1f53b621dd")
}
> db.indexesDemo.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de5825ddae1f53b621de")
}
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de6725ddae1f53b621df")
}
> db.indexesDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06de7225ddae1f53b621e0")
}

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

> db.indexesDemo.find();

This will produce the following output −

{ "_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" }

Following is the query to indexes −

> db.indexesDemo.find(
... { StudentFirstName: { $in: [ "John", "David" ] } },
... { _id: 0, StudentLastName: 0 }
... );

This will produce the following output −

{ "StudentFirstName" : "David" }
{ "StudentFirstName" : "John" }
{ "StudentFirstName" : "John" }

Updated on: 31-Mar-2020

854 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements