Combining unique items from arrays in MongoDB?


To combine unique items from array, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo420.insert(
...    {
...
...       "details" : [
...          {
...             "Value1":10,
...             "Value2":20,
...             "Value3":30
...          }
...       ]
...    }
... )
WriteResult({ "nInserted" : 1 })
> db.demo420.insert(
...    {
...
...       "Info" : [
...          {
...             "Value1":10,
...             "Value2":20,
...             "Value3":300
...          }
...       ]
...    }
... )
WriteResult({ "nInserted" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo420.find();

This will produce the following output −

{ "_id" : ObjectId("5e739a569822da45b30346dc"), "details" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 30 } ] }
{ "_id" : ObjectId("5e739a569822da45b30346dd"), "Info" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 300 } ] }

Following is the query to combine unique items from arrays −

> db.demo420.aggregate([
...    { "$project": {
...       "_id": 0,
...       "unique": {
...          "$filter": {
...             "input": {
...                "$setDifference": [
...                   { "$concatArrays": [
...                      "$Info.Value1",
...                      "$Info.Value2",
...                      "$Info.Value3"
...
...                   ]},
...                []
...             ]
...          },
...          "cond": { "$ne": [ "$$this", "" ] }
...       }
...    }
... }},
... { "$unwind": "$unique" },
... { "$group": {
...    "_id": null,
...    "uniqueArray": { "$addToSet": "$unique" }
... }}
... ])

This will produce the following output −

{ "_id" : null, "uniqueArray" : [ 300, 20, 10 ] }

Updated on: 03-Apr-2020

375 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements