Saturday 21 February 2015

mongoDB : Compound Indexes


You can create single index structure on multiple fields.


> db.sample.ensureIndex({a:1, b:-1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}


Above snippet creates compound index on fields ‘a’ and ‘b’.

> db.sample.find()
{ "_id" : ObjectId("54c8f40c889636817c7be6a3"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("54c8f451889636817c7be6a4"), "a" : 3, "b" : 4 }
>
>
> db.sample.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.sample"
        },
        {
                "v" : 1,
                "key" : {
                        "a" : 1,
                        "b" : -1
                },
                "name" : "a_1_b_-1",
                "ns" : "test.sample"
        }
]

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment