Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
MongoDB query to return only specific fields (phone numbers) in the form of an array?
To return only specific fields (phone numbers) as an array in MongoDB, use the distinct() method to extract unique values from nested fields across all documents in a collection.
Syntax
db.collection.distinct("field.path")
Sample Data
Let us create a collection with documents −
db.demo166.insertMany([
{
"details": {
"UserName": "Chris",
"UserAge": 29,
"PhoneDetails": {
"PhoneNumber": "98646463533"
}
}
},
{
"details": {
"UserName": "David",
"UserAge": 21,
"PhoneDetails": {
"PhoneNumber": "87664534654"
}
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e368b159e4f06af551997cf"),
ObjectId("5e368b159e4f06af551997d0")
]
}
Verify Sample Data
Display all documents from the collection −
db.demo166.find();
{
"_id": ObjectId("5e368b159e4f06af551997cf"),
"details": {
"UserName": "Chris",
"UserAge": 29,
"PhoneDetails": {
"PhoneNumber": "98646463533"
}
}
}
{
"_id": ObjectId("5e368b159e4f06af551997d0"),
"details": {
"UserName": "David",
"UserAge": 21,
"PhoneDetails": {
"PhoneNumber": "87664534654"
}
}
}
Extract Phone Numbers as Array
Use distinct() to return only phone numbers in array format −
db.demo166.distinct("details.PhoneDetails.PhoneNumber");
["98646463533", "87664534654"]
How It Works
The distinct() method traverses all documents and extracts unique values from the specified nested field path "details.PhoneDetails.PhoneNumber", automatically returning them as an array format.
Conclusion
Use db.collection.distinct("field.path") to efficiently extract specific nested field values as an array. This method automatically handles duplicates and returns only unique values across all documents in the collection.
