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

MongoDB에서 여러 키로 "고유"를 효율적으로 수행하는 방법은 무엇입니까?

<시간/>

집계 프레임워크를 사용하여 여러 키로 고유한 작업을 수행할 수 있습니다.

개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -

> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f74488d10a061296a3c53")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f744b8d10a061296a3c54")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f74598d10a061296a3c55")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f745e8d10a061296a3c56")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Carol","StudentAge":27,"StudentMathMarks":54});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f74688d10a061296a3c57")
}

find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -

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

다음은 출력입니다 -

{
   "_id" : ObjectId("5c7f74488d10a061296a3c53"),
   "StudentName" : "Mike",
   "StudentAge" : 22,
   "StudentMathMarks" : 56
}
{
   "_id" : ObjectId("5c7f744b8d10a061296a3c54"),
   "StudentName" : "Mike",
   "StudentAge" : 22,
   "StudentMathMarks" : 56
}
{
   "_id" : ObjectId("5c7f74598d10a061296a3c55"),
   "StudentName" : "Bob",
   "StudentAge" : 23,
   "StudentMathMarks" : 45
}
{
   "_id" : ObjectId("5c7f745e8d10a061296a3c56"),
   "StudentName" : "Bob",
   "StudentAge" : 23,
   "StudentMathMarks" : 45
}
{
   "_id" : ObjectId("5c7f74688d10a061296a3c57"),
   "StudentName" : "Carol",
   "StudentAge" : 27,
   "StudentMathMarks" : 54
}

다음은 여러 키를 사용하여 고유하게 수행하는 쿼리입니다. -

> c = db.distinctWithMultipleKeysDemo;
test.distinctWithMultipleKeysDemo
> myResult = c.aggregate( [ {"$group": { "_id": { StudentName:"$StudentName", StudentAge: "$StudentAge" } } } ] );

다음은 출력입니다 -

{ "_id" : { "StudentName" : "Carol", "StudentAge" : 27 } }
{ "_id" : { "StudentName" : "Bob", "StudentAge" : 23 } }
{ "_id" : { "StudentName" : "Mike", "StudentAge" : 22 } }