Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB에서 인덱스가 있는 여러 필드의 중복 방지

<시간/>

여러 필드의 중복을 방지하려면sureIndex()를 사용하고 unique:true를 설정하십시오. 문서로 컬렉션을 만들자 −

> db.demo272.ensureIndex({"FirstName":1,"Subject":1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo272.insertOne({"FirstName":"Chris","Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48232a1627c0c63e7dbabf")
}
> db.demo272.insertOne({"FirstName":"Chris","Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48232f1627c0c63e7dbac0")
}
> db.demo272.insertOne({"FirstName":"David","Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48233a1627c0c63e7dbac1")
}
> db.demo272.insertOne({"FirstName":"Chris","Subject":"MySQL"});
2020-02-15T22:28:55.137+0530 E QUERY    [js] WriteError: E11000 duplicate key error collection: test.demo272 index: FirstName_1_Subject_1 dup key: { : "Chris", : "MySQL" } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: test.demo272 index: FirstName_1_Subject_1 dup key: { : \"Chris\", : \"MySQL\" }",
   "op" : {
      "_id" : ObjectId("5e48234f1627c0c63e7dbac2"),
      "FirstName" : "Chris",
      "Subject" : "MySQL"
   }
})
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.demo272.find();

이것은 다음과 같은 출력을 생성합니다 -

{ "_id" : ObjectId("5e48232a1627c0c63e7dbabf"), "FirstName" : "Chris", "Subject" : "MySQL" }
{ "_id" : ObjectId("5e48232f1627c0c63e7dbac0"), "FirstName" : "Chris", "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e48233a1627c0c63e7dbac1"), "FirstName" : "D
okavid", "Subject" : "MySQL" }