예,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 }