I MongoDB, $orderBy frågemodifierare sorterar resultaten av en fråga i stigande eller fallande ordning.
$orderBy accepterar ett dokument som anger fältet som ska sorteras och sorteringsordningen. Sorteringsordningen kan vara antingen 1 för stigande eller -1 för nedstigning.
$orderBy har fasats ut i mongo skal sedan v3.2. Använd cursor.sort() metod istället.
Exempeldata
Anta att vi har en samling som heter pets med följande dokument:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 5, "name" : "Bruce", "type" : "Kangaroo", "weight" : 100 }
{ "_id" : 6, "name" : "Hop", "type" : "Kangaroo", "weight" : 130 }
{ "_id" : 7, "name" : "Punch", "type" : "Kangaroo", "weight" : 200 }
{ "_id" : 8, "name" : "Snap", "type" : "Cat", "weight" : 12 }
{ "_id" : 9, "name" : "Ruff", "type" : "Dog", "weight" : 30 } Sortera i stigande ordning
För att sortera i stigande ordning använder vi 1 för sorteringsordningen.
Nedan är ett exempel på en fråga som använder $orderBy frågemodifierare för att sortera den samlingen efter weight fältet i stigande ordning.
db.pets.find( { $query: {}, $orderBy: { weight: 1 } } ) Resultat:
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 8, "name" : "Snap", "type" : "Cat", "weight" : 12 }
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 9, "name" : "Ruff", "type" : "Dog", "weight" : 30 }
{ "_id" : 5, "name" : "Bruce", "type" : "Kangaroo", "weight" : 100 }
{ "_id" : 6, "name" : "Hop", "type" : "Kangaroo", "weight" : 130 }
{ "_id" : 7, "name" : "Punch", "type" : "Kangaroo", "weight" : 200 } Sortera i fallande ordning
För att sortera i fallande ordning använder vi -1 för sorteringsordningen.
db.pets.find( { $query: {}, $orderBy: { weight: -1 } } ) Resultat:
{ "_id" : 7, "name" : "Punch", "type" : "Kangaroo", "weight" : 200 }
{ "_id" : 6, "name" : "Hop", "type" : "Kangaroo", "weight" : 130 }
{ "_id" : 5, "name" : "Bruce", "type" : "Kangaroo", "weight" : 100 }
{ "_id" : 9, "name" : "Ruff", "type" : "Dog", "weight" : 30 }
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 8, "name" : "Snap", "type" : "Cat", "weight" : 12 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } En alternativ form
$orderBy query modifier kan också användas med följande form:
db.pets.find()._addSpecial( "$orderby", { weight : 1 } ) Mer information
Som nämnts, $orderBy frågemodifierare har fasats ut i mongo skal sedan v3.2. Använd cursor.sort() metod istället.
Se MongoDB-dokumentationen för mer information.