Tuesday, June 30, 2015

Indexes in MongoDB

Create Index
> db.Customer.ensureIndex({"CustCode":1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.Customer.find()
> db.Customer.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "testdb.Customer"
        },
        {
                "v" : 1,
                "key" : {
                        "CustCode" : 1
                },
                "name" : "CustCode_1",
                "ns" : "testdb.Customer"
        }
]
>
> db.Customer.createIndex({"CustCode":1},{unique:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}
> db.Customer.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "testdb.Customer"
        },
        {
                "v" : 1,
                "key" : {
                        "_id" : 1,
                        "CustCode" : 1
                },
                "name" : "_id_1_CustCode_1",
                "ns" : "testdb.Customer"
        },
        {
                "v" : 1,
                "unique" : true,
                "key" : {
                        "CustCode" : 1
                },
                "name" : "CustCode_1",
                "ns" : "testdb.Customer"
        }
]
> db.Customer.insert({"CustCode":2,"Name":"Customer2"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: testdb.Customer
.$CustCode_1  dup key: { : 2.0 }"
        }
})
>

No comments:

Post a Comment