為 MongoDB 複合索引設定固定值欄位


為此,我們將使用 createIndex() 和 create index − 的概念

> db.compoundIndexDemo.createIndex({"StudentName":1,"StudentAge":1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

我們首先使用文件建立一個集合 −

> db.compoundIndexDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c1d25ddae1f53b62207")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c5625ddae1f53b62209")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c5b25ddae1f53b6220a")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
2019-12-29T12:19:02.225+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: web.compoundIndexDemo index:                StudentName_1_StudentAge_1 dup key: { : \"Chris\", : 23.0 }",
   "op" : {
      "_id" : ObjectId("5e084c5e25ddae1f53b6220b"),
      "StudentName" : "Chris",
      "StudentAge" : 23
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1

以下是使用 find() 方法顯示集合中所有文件的查詢 −

> db.compoundIndexDemo.find().pretty();

這將產生以下輸出 −

{ "_id" : ObjectId("5e084c1d25ddae1f53b62207"), "StudentName" : "Chris" }
{
      "_id" : ObjectId("5e084c5625ddae1f53b62209"),
      "StudentName" : "Chris",
      "StudentAge" : 23
}
{
   "_id" : ObjectId("5e084c5b25ddae1f53b6220a"),
   "StudentName" : "Chris",
   "StudentAge" : 22
}

更新於:2020 年 3 月 31 日

138 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.