Saturday 21 February 2015

mongoDB : Unique indexes


mongoDB supports unique indexes.

db.student.ensureIndex({"mailid" : 1}, {"unique" : true})
Above statement creates unique index on field mailid. If you set "unique" to true, it creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.

> db.student.find()
{ "_id" : 1, "name" : "hari krishna", "mailid" : "abcabc@abc.com" }
>
> db.student.ensureIndex({"mailid" : 1}, {"unique" : true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>    


When you try to insert other document with mailed “abcabc@abc.com”, you will get error.

> db.student.insert({"_id" : 2, "name" : "Krishna", "mailid" : "abcabc@abc.com"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.student.$mailid_1  dup key: { : \"abcabc@abc.com\" }"
        }
})
>

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment