Unique index field in MongoDB

Creating a unique index field in MongoDB

An index is a MongoDB feature that allow us to retrive and query our collections in a quick and efficient way. In general an index is an ordered list of all the values of a particular field inside a collection. Every index has a pointer to the full document that it belongs to.

Result

db.articles.createIndex({name: 1}, {unique: true})

Result

{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

The _id field is a unique index, that's why numIndexesAfter is equal to 2

Listing our indexes

db.articles.getIndexes()

Result

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "yamicode.articles"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "name" : 1
                },
                "name" : "name_1",
                "ns" : "yamicode.articles"
        }
]

The name of the index is generated by default and is a combination of the name of the field and the order, Also as mentioned it's unique and applied for the field name

Tesing

In this test we'll try to add two documents that has the same field name, and we'll get a duplicated key error to demonstrate that the field is a unique index

>db.articles.insert({name: "article1"})
WriteResult({ "nInserted" : 1 })

>db.articles.insert({name: "article1"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: yamicode.articles index: name_1 dup key: { name: \"article1\" }"
        }
})