MongoDB
Indexes
Unique index
To prevent duplicated records when inserting new document into MongoDB collection with:
> db.neki_collection.insert({'var':'val'})
create unique index:
> db.neki_collection.createIndex({"page_url": 1}, {unique: true})
> db.content.createIndex({pageURL:1},{name:"pageURL", unique:true})
drop the index
>db.neki_collection.dropIndex({"page_url": 1}) - drop by index definition
>db.content.dropIndex("pageURL") - drop by index name
create index and name it:
>db.neki_collection.createIndex({"cid": -1, "title": 1}, {name: "myIndex"})
- cid has descending order (from greater to smaller value)
- title is ordered ascending (from smaller to greater, or from A to Z)
- index is named with "myIndex"
In the above example unique index is created for page_url field.
To check indexes use:
> db.neki_collection.getIndexes()
[
{
"v" : 1,
"name" : "_id_",
"key" : {
"_id" : 1
},
"ns" : "crawler.ads"
},
{
"v" : 1,
"name" : "page_url_1",
"key" : {
"page_url" : 1
},
"unique" : true,
"ns" : "crawler.ads"
}
]