$sort

La fase $sort nella pipeline di aggregazione viene usata per ordinare i documenti nella pipeline in base a un campo o a campi specificati. Questa fase consente di ordinare i dati, ad esempio organizzando le vendite in base all'importo o agli eventi in base alla data.

Sintassi

{
    $sort: {
        < field1 >: < sort order > ,
        < field2 >: < sort order >
    }
}

Parametri

Parametro Description
field Campo in base al quale eseguire l'ordinamento
sort order Ordine in cui è necessario ordinare il campo. 1 per l'ordine crescente e -1 per l'ordine decrescente.

Esempi

Si consideri questo documento di esempio dalla raccolta negozi.

{
    "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
    "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
    "location": {
        "lat": -89.2384,
        "lon": -46.4012
    },
    "staff": {
        "totalStaff": {
            "fullTime": 8,
            "partTime": 20
        }
    },
    "sales": {
        "totalSales": 75670,
        "salesByCategory": [
            {
                "categoryName": "Wine Accessories",
                "totalSales": 34440
            },
            {
                "categoryName": "Bitters",
                "totalSales": 39496
            },
            {
                "categoryName": "Rum",
                "totalSales": 1734
            }
        ]
    },
    "promotionEvents": [
        {
            "eventName": "Unbeatable Bargain Bash",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 23
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 7,
                    "Day": 2
                }
            },
            "discounts": [
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 7
                },
                {
                    "categoryName": "Bitters",
                    "discountPercentage": 15
                },
                {
                    "categoryName": "Brandy",
                    "discountPercentage": 8
                },
                {
                    "categoryName": "Sports Drinks",
                    "discountPercentage": 22
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 19
                }
            ]
        },
        {
            "eventName": "Steal of a Deal Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 29
                }
            },
            "discounts": [
                {
                    "categoryName": "Organic Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "White Wine",
                    "discountPercentage": 20
                },
                {
                    "categoryName": "Sparkling Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 17
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 23
                }
            ]
        }
    ]
}

Esempio 1: Ordinamento in base alle vendite totali nell'ordine di sescending

Per ordinare le categorie di vendita in base alle vendite totali in ordine decrescente:

db.collection.aggregate([
  {
    $unwind: "$store.sales.salesByCategory"
  },
  {
    $sort: { "store.sales.salesByCategory.totalSales": -1 }
  }
])

I primi due risultati restituiti da questa query sono:

[
    {
        "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
        "store": {
            "name": "Downtown Store",
            "sales": {
                "salesByCategory": [
                    {
                        "category": "Electronics",
                        "totalSales": 15000
                    },
                    {
                        "category": "Clothing",
                        "totalSales": 12000
                    },
                    {
                        "category": "Home Goods",
                        "totalSales": 10000
                    }
                ]
            }
        }
    },
    {
        "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6",
        "store": {
            "name": "Uptown Store",
            "sales": {
                "salesByCategory": [
                    {
                        "category": "Electronics",
                        "totalSales": 20000
                    },
                    {
                        "category": "Clothing",
                        "totalSales": 18000
                    },
                    {
                        "category": "Home Goods",
                        "totalSales": 15000
                    }
                ]
            }
        }
    }
]

Esempio 2: Ordinamento in base alla data di inizio dell'evento in ordine crescente

Per ordinare gli eventi promozionali in base alle date di inizio in ordine crescente:

db.collection.aggregate([
  {
    $unwind: "$store.promotionEvents"
  },
  {
    $sort: { "store.promotionEvents.promotionalDates.startDate": 1 }
  }
])

I primi due risultati restituiti da questa query sono:

[
    {
        "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
        "store": {
            "name": "Downtown Store",
            "promotionEvents": [
                {
                    "eventName": "Summer Sale",
                    "promotionalDates": {
                        "startDate": "2024-06-01T00:00:00Z",
                        "endDate": "2024-06-30T23:59:59Z"
                    }
                },
                {
                    "eventName": "Black Friday",
                    "promotionalDates": {
                        "startDate": "2024-11-25T00:00:00Z",
                        "endDate": "2024-11-25T23:59:59Z"
                    }
                },
                {
                    "eventName": "Holiday Deals",
                    "promotionalDates": {
                        "startDate": "2024-12-01T00:00:00Z",
                        "endDate": "2024-12-31T23:59:59Z"
                    }
                }
            ]
        }
    },
    {
        "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6",
        "store": {
            "name": "Uptown Store",
            "promotionEvents": [
                {
                    "eventName": "Back to School",
                    "promotionalDates": {
                        "startDate": "2024-08-01T00:00:00Z",
                        "endDate": "2024-08-31T23:59:59Z"
                    }
                },
                {
                    "eventName": "Winter Sale",
                    "promotionalDates": {
                        "startDate": "2024-12-01T00:00:00Z",
                        "endDate": "2024-12-31T23:59:59Z"
                    }
                }
            ]
        }
    }
]

Esempio 3: Ordinamento di una matrice di oggetti

L'esempio ordina la salesByCategory matrice sul posto in base al totalSales campo in ordine crescente.

db.stores.updateOne({
            _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
        }, {
            $push: {
                "sales.salesByCategory": {
                    $each: [],
                    $sort: {
                        totalSales: 1
                    }
                }
            }
        }
)