- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB transaction & indexes for duplicate values
Use ensureIndex() and set unique:1 inside the array. Let us create a collection with documents −
> db.demo298.save({Name: 'Chris', Marks: [46, 79] }); WriteResult({ "nInserted" : 1 }) > db.demo298.save({Name: 'David', Marks: [67, 88] }); WriteResult({ "nInserted" : 1 }) > db.demo298.ensureIndex({ Marks: 1 }, {unique: 1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo298.save({Name: 'Mike', Marks: [88,98] }); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo298 index: Marks_1 dup key: { : 88.0 }" } })
Display all documents from a collection with the help of find() method −
> db.demo298.find();
This will produce the following output −
{ "_id" : ObjectId("5e4d56e55d93261e4bc9ea48"), "Name" : "Chris", "Marks" : [ 46, 79 ] } { "_id" : ObjectId("5e4d56f55d93261e4bc9ea49"), "Name" : "David", "Marks" : [ 67, 88 ] }
Advertisements