

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 }
- Related Questions & Answers
- Check for duplicates in an array in MongoDB?
- List all values of a certain field in MongoDB?
- Want to update inner field in a MongoDB
- Accessing inner element of JSON array in MongoDB?
- MongoDB Aggregate JSON array field for the matching field of other collection?
- How to sort inner array in MongoDB?
- Insert data into inner array in MongoDB?
- Reverse array field in MongoDB?
- Check if value exists for a field in a MongoDB document?
- Find items that do not have a certain field in MongoDB?
- Get distinct levels of array field in MongoDB?
- Check that Field Exists with MongoDB?
- MongoDB slice array in populated field?
- MongoDB query for a single field
- Sorting field value (FirstName) for MongoDB?
Advertisements