Tutorialspoint

Is it possible to return a list of specific values from a MongoDB query?


1 Answer
Chandu yadav

Yes, using map(). Let us first create a collection with documents −

> dblistOfSpecificValuesDemoinsertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefcc8fef71edecf6a1f6bb")
}
> dblistOfSpecificValuesDemoinsertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefcc94ef71edecf6a1f6bc")
}
> dblistOfSpecificValuesDemoinsertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefcc98ef71edecf6a1f6bd")
}
> dblistOfSpecificValuesDemoinsertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefcc9cef71edecf6a1f6be")
}

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

> dblistOfSpecificValuesDemofind();

Output

{ "_id" : ObjectId("5cefcc8fef71edecf6a1f6bb"), "StudentName" : "John" }
{ "_id" : ObjectId("5cefcc94ef71edecf6a1f6bc"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cefcc98ef71edecf6a1f6bd"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5cefcc9cef71edecf6a1f6be"), "StudentName" : "David" }

Following is the query to return a list of specific values from a query −

> dblistOfSpecificValuesDemofind()map(function(myDocument){ return myDocumentStudentName });

Output

[ "John", "Chris", "Robert", "David" ]

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.