To return a list of specific values, use map(). Let us create a collection with documents −
> db.demo195.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3f203d395bdc21346d4") } > db.demo195.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3f703d395bdc21346d5") } > db.demo195.insertOne({"Subject":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3fa03d395bdc21346d6") }
Display all documents from a collection with the help of find() method −
> db.demo195.find();
This will produce the following output −
{ "_id" : ObjectId("5e3af3f203d395bdc21346d4"), "Subject" : "MySQL" } { "_id" : ObjectId("5e3af3f703d395bdc21346d5"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e3af3fa03d395bdc21346d6"), "Subject" : "Java" }
Following is the query to return a list of specific values from a query −
> db.demo195.find().map(function(doc){ return doc.Subject });
This will produce the following output −
[ "MySQL", "MongoDB", "Java" ]