이를 위해 간단히 MongoDB $group을 사용하십시오. 먼저 문서로 컬렉션을 만들어 보겠습니다. −
> db.demo16.insertOne({
... "StudentName" : "Chris",
... "StudentSection" : "A",
... "StudentAge" : 23,
... "StudentMarks" : 47
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827455d0fc6657d21f07")
}
> db.demo16.insertOne({
... "StudentName" : "Bob",
... "StudentSection" : "B",
... "StudentAge" : 21,
... "StudentMarks" : 85
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827555d0fc6657d21f08")
}
> db.demo16.insertOne( {
... "StudentName" : "Carol",
... "StudentSection" : "A",
... "StudentAge" : 26,
... "StudentMarks" : 97
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827655d0fc6657d21f09")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.demo16.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5e13827455d0fc6657d21f07"),
"StudentName" : "Chris",
"StudentSection" : "A",
"StudentAge" : 23,
"StudentMarks" : 47
}
{
"_id" : ObjectId("5e13827555d0fc6657d21f08"),
"StudentName" : "Bob",
"StudentSection" : "B",
"StudentAge" : 21,
"StudentMarks" : 85
}
{
"_id" : ObjectId("5e13827655d0fc6657d21f09"),
"StudentName" : "Carol",
"StudentSection" : "A",
"StudentAge" : 26,
"StudentMarks" : 97
} 다음은 그룹 및 개별 작업을 함께 구현하는 쿼리입니다. −
> db.demo16.aggregate([{
... $group : {
... _id : null,
... StudentName : { $addToSet : "$StudentName" },
... StudentSection : { $addToSet : "$StudentSection" },
... StudentMinimumAge : { $min : "$StudentAge" },
... StudentMaximumAge : { $max : "$StudentAge" },
... StudentMinimumMarks: { $min : "$StudentMarks" },
... StudentMaximumMarks : { $max : "$StudentMarks" }
... }
... }]).pretty(); 이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : null,
"StudentName" : [
"Carol",
"Bob",
"Chris"
],
"StudentSection" : [
"B",
"A"
],
"StudentMinimumAge" : 21,
"StudentMaximumAge" : 26,
"StudentMinimumMarks" : 47,
"StudentMaximumMarks" : 97
}