Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Check Duplicates of Certain Field for Inner Array in MongoDB



To check duplicates in the inner array, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo347.insertOne(
...    {
...       "details": {
...          "details1": [
...             {
...                Name: "Chris",
...                Age: 21
...             }
...
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5532eaf8647eb59e5620af")
}
> db.demo347.insertOne(
...    {
...       "details": {
...          "details1": [
...             {
...                Name: "David",
...                Age: 22
...             }
...
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e55330af8647eb59e5620b0")
}
> db.demo347.insertOne(
...    {
...       "details": {
...          "details1": [
...             {
...                Name: "Chris",
...                Age: 21
...             }
...
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e55331cf8647eb59e5620b1")
}

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

> db.demo347.find();

This will produce the following output −

{ "_id" : ObjectId("5e5532eaf8647eb59e5620af"), "details" : { "details1" : [ { "Name" : "Chris", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e55330af8647eb59e5620b0"), "details" : { "details1" : [ { "Name" : "David", "Age" : 22 } ] } }
{ "_id" : ObjectId("5e55331cf8647eb59e5620b1"), "details" : { "details1" : [ { "Name" : "Chris", "Age" : 21 } ] } }

Following is the query to check duplicates of the certain field −

> db.demo347.aggregate([
...    {"$unwind": "$details"},
...    {"$unwind": "$details.details1"},
...    {"$group" : { "_id": "$details.details1.Name", "count": { "$sum": 1 } } },
...    {"$match": { "_id" :{ "$ne" : null } , "count" : { "$gt": 1} } }
... ])

This will produce the following output −

{ "_id" : "Chris", "count" : 2 }
Updated on: 2020-04-02T07:48:40+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements