 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Retrieving group by result with arrays in MongoDB?
To retrieve group by result with arrays, use aggregate(). We will also use $addToSet operator. It adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
Let us create a collection with documents −
> db.demo498.insertOne({id:1,Name:["Chris"]});{    "acknowledged" : true,    "insertedId" : ObjectId("5e86192b987b6e0e9d18f553") } > db.demo498.insertOne({id:2,Name:["David"]});{    "acknowledged" : true,    "insertedId" : ObjectId("5e86192d987b6e0e9d18f554") } > db.demo498.insertOne({id:3,Name:["Chris"]});{    "acknowledged" : true,    "insertedId" : ObjectId("5e861931987b6e0e9d18f555") } > db.demo498.insertOne({id:4,Name:["Bob"]});{    "acknowledged" : true,    "insertedId" : ObjectId("5e861942987b6e0e9d18f556") } > db.demo498.insertOne({id:5,Name:["David"]});{    "acknowledged" : true,    "insertedId" : ObjectId("5e861947987b6e0e9d18f557") } Display all documents from a collection with the help of find() method −
> db.demo498.find();
This will produce the following output −
{ "_id" : ObjectId("5e86192b987b6e0e9d18f553"), "id" : 1, "Name" : [ "Chris" ] } { "_id" : ObjectId("5e86192d987b6e0e9d18f554"), "id" : 2, "Name" : [ "David" ] } { "_id" : ObjectId("5e861931987b6e0e9d18f555"), "id" : 3, "Name" : [ "Chris" ] } { "_id" : ObjectId("5e861942987b6e0e9d18f556"), "id" : 4, "Name" : [ "Bob" ] } { "_id" : ObjectId("5e861947987b6e0e9d18f557"), "id" : 5, "Name" : [ "David" ] } Following is the query to retrieve group by result with arrays in MongoDB −
> db.demo498.aggregate([{ ...    $unwind : "$Name" ... }, { ...       $group : { ...          _id : $quot;$Name", ...          Id : { ...             $addToSet : "$id" ...          } ...       } ...    } ... ]) This will produce the following output −
{ "_id" : "David", "Id" : [ 5, 2 ] } { "_id" : "Bob", "Id" : [ 4 ] } { "_id" : "Chris", "Id" : [ 3, 1 ] }Advertisements
 