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
List all values of a certain field in MongoDB?
To get the list of all values of certain fields in MongoDB, you can use distinct(). The syntax is as follows −
db.yourCollectionName.distinct( "yourFieldName");
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fc89ed3c9d04998abf011")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,60]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fc8abd3c9d04998abf012")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fc8d7d3c9d04998abf013")
}
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,70]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fc8e2d3c9d04998abf014")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.listAllValuesOfCeratinFieldsDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8fc89ed3c9d04998abf011"),
"ListOfValues" : [
10,
20,
30
]
}
{
"_id" : ObjectId("5c8fc8abd3c9d04998abf012"),
"ListOfValues" : [
40,
50,
60
]
}
{
"_id" : ObjectId("5c8fc8d7d3c9d04998abf013"),
"ListOfValues" : [
10,
20,
30
]
}
{
"_id" : ObjectId("5c8fc8e2d3c9d04998abf014"),
"ListOfValues" : [
40,
50,
70
]
}
Here is the query to get the list all values of a certain field in MongoDB. We are displaying the record of the field ‘ListOfValues’ −
> db.listAllValuesOfCeratinFieldsDemo.distinct( "ListOfValues");
The following is the output −
[ 10, 20, 30, 40, 50, 60, 70 ]
Advertisements