MongoDB 집계에서 $sort를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo652.insertOne({
... value:10,
... "details" : [{
... "ProductName" : "Product-1",
... "ProductQuantity" : 8,
... "ProductPrice" : 500
... }, {
... "ProductName" : "Product-2",
... "ProductQuantity" : 7,
... "ProductPrice" : 500
...
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62")
}
>
> db.demo652.insertOne({
... value:5,
... "details" : [{
... "ProductName" : "Product-1",
... "ProductQuantity" : 8,
... "ProductPrice" : 500
... }, {
... "ProductName" : "Product-2",
... "ProductQuantity" : 7,
... "ProductPrice" : 500
...
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo652.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
{ "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] } 다음은 오름차순으로 정렬하는 쿼리입니다 -
> db.demo652.aggregate([{
... "$unwind": "$details"
... }, {
... "$match": {}
... }, {
... "$group": {
... "ProductPrice": {
... "$first": "$value"
... },
... "details": {
... "$push": {
... "ProductName": "$details.ProductName"
... }
... },
... "_id": "$_id"
... }
... }, {
... "$sort": {
... "ProductPrice": 1
... }
... }, {
... "$project": {
... "_id": 0,
... "ProductPrice": 1,
... "details": 1
... }
... }]).pretty() 이것은 다음과 같은 출력을 생성합니다 -
{
"ProductPrice" : 5,
"details" : [
{
"ProductName" : "Product-1"
},
{
"ProductName" : "Product-2"
}
]
}
{
"ProductPrice" : 10,
"details" : [
{
"ProductName" : "Product-1"
},
{
"ProductName" : "Product-2"
}
]
}