MongoDB query to return only specific fields (phone numbers) in the form of an array?

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo166.insertOne({"details" : { "UserName" : "Chris", "UserAge":29, "PhoneDetails" : { "PhoneNumber" : "98646463533" } } });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e368b159e4f06af551997cf")
}
> db.demo166.insertOne({"details" : { "UserName" : "David", "UserAge":21, "PhoneDetails" : { "PhoneNumber" : "87664534654" } } });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e368b159e4f06af551997d0")
}

Display all documents from a collection with the help of find() method −

> db.demo166.find();

This will produce the following output −

{ "_id" : ObjectId("5e368b159e4f06af551997cf"), "details" : { "UserName" : "Chris", "UserAge" : 29, "PhoneDetails" : { "PhoneNumber" : "98646463533" } } }
{ "_id" : ObjectId("5e368b159e4f06af551997d0"), "details" : { "UserName" : "David", "UserAge" : 21, "PhoneDetails" : { "PhoneNumber" : "87664534654" } } }

Following is the query to return only specific fields (phone numbers) in the form of an array −

> db.demo166.distinct("details.PhoneDetails.PhoneNumber");

This will produce the following output −

[ "98646463533", "87664534654" ]
raja
Published on 01-Apr-2020 11:57:52
Advertisements