Check duplicates of certain field for inner array in MongoDB

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 02-Apr-2020 11:17:12
Advertisements