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 projection result as an array of selected items?
In MongoDB, projection results as an array of selected items can be achieved using the distinct() method. This method returns an array of distinct values for a specified field from documents that match the given query criteria.
Syntax
db.collection.distinct(field, query)
Where field is the field to return distinct values from, and query is the optional filter criteria.
Sample Data
Let us create a collection with documents:
db.demo151.insertMany([
{"ListOfNames": ["Chris", "David", "Mike"]},
{"ListOfNames": ["Mike", "Bob"]},
{"ListOfNames": ["John", "David", "Chris"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3513b6fdf09dd6d08539da"),
ObjectId("5e3513c4fdf09dd6d08539db"),
ObjectId("5e3513dcfdf09dd6d08539dc")
]
}
View Sample Data
db.demo151.find();
{ "_id": ObjectId("5e3513b6fdf09dd6d08539da"), "ListOfNames": ["Chris", "David", "Mike"] }
{ "_id": ObjectId("5e3513c4fdf09dd6d08539db"), "ListOfNames": ["Mike", "Bob"] }
{ "_id": ObjectId("5e3513dcfdf09dd6d08539dc"), "ListOfNames": ["John", "David", "Chris"] }
Example: Get Array of Document IDs
To get an array of _id values from documents where the ListOfNames array contains "Mike":
db.demo151.distinct('_id', {'ListOfNames': "Mike"});
[
ObjectId("5e3513b6fdf09dd6d08539da"),
ObjectId("5e3513c4fdf09dd6d08539db")
]
More Examples
Get all distinct names from the ListOfNames arrays:
db.demo151.distinct('ListOfNames');
["Bob", "Chris", "David", "John", "Mike"]
Conclusion
The distinct() method efficiently projects results as an array of unique values from specified fields. It's particularly useful for extracting specific field values based on query conditions without retrieving entire documents.
