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

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



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" ]
Updated on: 2020-04-01T11:58:22+05:30

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements