배열 항목을 그룹화하려면 $sort와 함께 $group을 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo566.insertOne(
... {
...
... "ProductInformation" : [
... {
... "ProductName" : "Product-1",
... "ProductPrice" :100
... },
... {
... "ProductName" : "Product-2",
... "ProductPrice" :1100
... },
... {
... "ProductName" : "Product-3",
... "ProductPrice" :100
... },
... {
... "ProductName" : "Product-4",
... "ProductPrice" :1100
... },
... {
... "ProductName" : "Product-5",
... "ProductPrice" :100
... }
... ]
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo566.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "ProductInformation" : [
{ "ProductName" : "Product-1", "ProductPrice" : 100 },
{ "ProductName" : "Product-2", "ProductPrice" : 1100 },
{ "ProductName" : "Product-3", "ProductPrice" : 100 },
{ "ProductName" : "Product-4", "ProductPrice" : 1100 },
{ "ProductName" : "Product-5", "ProductPrice" : 100 }
] } 다음은 배열 항목을 그룹화하는 쿼리입니다 -
> db.demo566.aggregate([
... {
... "$unwind": "$ProductInformation"
... },
... {
... "$group": {
... "_id": "$ProductInformation.ProductPrice",
... "Value": { "$sum" : 1 }
... }
... },
... { "$sort": { "_id" :1 } }
... ]) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : 100, "Value" : 3 }
{ "_id" : 1100, "Value" : 2 }