
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Query to Return Specific Fields as Phone Numbers 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" ]
Advertisements