이를 위해 createIndex() 개념을 사용하고 인덱스 생성 -
> 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 }