Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 知乎專欄 | 視頻教程 | About

14.12. Indexes 索引

增加索引:1(ascending),-1(descending)

14.12.1. 查看索引

		
db.getCollection('product').getIndexes() 		
		
		
		
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "uuid" : 1
        },
        "name" : "uuid",
        "ns" : "netkiller.product",
        "sparse" : true
    },
    {
        "v" : 2,
        "key" : {
            "nfc" : 1
        },
        "name" : "nfc",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "qrcode" : 1
        },
        "name" : "qrcode",
        "ns" : "netkiller.product",
        "sparse" : true
    },
    {
        "v" : 2,
        "key" : {
            "memberId" : 1
        },
        "name" : "memberId",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "transactionId" : 1
        },
        "name" : "transactionId",
        "ns" : "netkiller.product",
        "sparse" : true
    }
]		
		
		

查看索引信息

		
db.logging.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "logging.logging",
		"name" : "_id_"
	}
]		
		
		

查看索引名與排序方式

		
db.getCollection('member').getIndexKeys();

[
    {
        "_id" : 1
    },
    {
        "mobile" : 1
    },
    {
        "username" : 1
    },
    {
        "wechat" : 1
    }
]
		
		
		

14.12.2. 創建索引

增加索引

		
db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});		
		
		

索引子對象

		
db.logging.users.ensureIndex({address.city:1})
		
		

14.12.3. 刪除索引

		
db.getCollection('product').dropIndex("memberId")		
		
		

根據索引名刪除索引

		
> db.logging.users.dropIndex('name_1')
{ "nIndexesWas" : 2, "ok" : 1 }

> db.logging.users.getIndexKeys()
[ { "_id" : 1 } ]
		
		

14.12.4. 唯一索引

		
db.members.createIndex( { "user_id": 1 }, { unique: true } )		
		
		
		
> db.apple.createIndex({"devicetoken":1},{unique: true})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
		
		

14.12.5. 復合索引

		
db.getCollection('foo').ensureIndex({"address":1,"phone":1})		
		
		

14.12.6. 稀疏索引

		
db.getCollection('article').ensureIndex({"uuid": 1}, {"unique": true,"sparse":true});
		
		

作用, 唯一索引只允許一條索引欄位為空的記錄存在,之後就不允許插入了。再次插入為 null 的記錄時會報錯:

		
E11000 duplicate key error index: dup key: { : null };	
		
		

“sparse”的作用就是當 uuid 在文檔中不存在,或為空值,則不進入索引,從而避免上述問題。