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
Group all documents with common fields in MongoDB?
For this, use the $addToSet operator. Let us first create a collection with documents −
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":1,
"UserName":"Carol"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51200")
}
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":2,
"UserName":"David"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51201")
}
>
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":1,
"UserName":"Sam"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51202")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentWithCommonFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdf8ebebf3115999ed51200"), "UserId" : 1, "UserName" : "Carol" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51201"), "UserId" : 2, "UserName" : "David" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51202"), "UserId" : 1, "UserName" : "Sam" }
Following is the query to find all documents with common fields in MongoDB −
> db.findDocumentWithCommonFieldsDemo.aggregate({$group : {_id : "$UserId", "UserDetails": {$addToSet : "$UserName"}}});
This will produce the following output −
{ "_id" : 2, "UserDetails" : [ "David" ] }
{ "_id" : 1, "UserDetails" : [ "Sam", "Carol" ] }Advertisements