ใช่ คุณสามารถใช้sureIndex() MongoDB ให้การสนับสนุนอย่างสมบูรณ์สำหรับดัชนีบนฟิลด์ใด ๆ ในชุดเอกสาร
ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo622.ensureIndex({_id:1,Name:1,Age:1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo622.insertOne({_id:101,Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : 101 } > db.demo622.insertOne({_id:102,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 102 } > db.demo622.insertOne({_id:103,Name:"Bob",Age:21}); { "acknowledged" : true, "insertedId" : 103 } > db.demo622.insertOne({_id:104,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 104 } > db.demo622.insertOne({_id:104,Name:"Chris",Age:22}); 2020-04-18T12:21:18.085+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 }", "op" : { "_id" : 104, "Name" : "Chris", "Age" : 22 } }) 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 > db.demo622.insertOne({_id:105,Name:"Chris",Age:22}); { "acknowledged" : true, "insertedId" : 105 }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo622.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 101, "Name" : "Chris", "Age" : 21 } { "_id" : 102, "Name" : "Chris", "Age" : 22 } { "_id" : 103, "Name" : "Bob", "Age" : 21 } { "_id" : 104, "Name" : "Chris", "Age" : 22 } { "_id" : 105, "Name" : "Chris", "Age" : 22 }