Mongodb:如何按多个字段排序
您可以使用以下语法按多个字段对 MongoDB 中的文档进行排序:
db.myCollection.find().sort( { " field1 ": 1, " field2 ": -1 } )
此特定代码首先按字段 1升序对名为myCollection 的集合中的文档进行排序,然后按字段 2降序排序。
以下示例展示了如何在具有以下文档的催收团队中使用此语法:
db.teams.insertOne({team: " Mavs ", points: 30, rebounds: 8})
db.teams.insertOne({team: " Spurs ", points: 30, rebounds: 12})
db.teams.insertOne({team: " Rockets ", points: 20, rebounds: 7})
db.teams.insertOne({team: " Warriors ", points: 25, rebounds: 5})
db.teams.insertOne({team: " Cavs ", points: 25, rebounds: 9})
示例1:MongoDB中按多个字段排序(升序)
我们可以使用以下代码对Teams集合中的文档进行排序,首先增加“points”,然后增加“bounces”:
db.teams.find().sort( { " points ": 1, " rebounds ": 1 } )
该查询返回以下结果:
{ _id: ObjectId("61f952c167f1c64a1afb203b"),
team: 'Rockets',
points: 20,
rebounds: 7 }
{ _id: ObjectId("61f952c167f1c64a1afb203c"),
team: 'Warriors',
points: 25,
rebounds: 5 }
{ _id: ObjectId("61f952c167f1c64a1afb203d"),
team: 'Cavs',
points: 25,
rebounds: 9 }
{ _id: ObjectId("61f952c167f1c64a1afb2039"),
team: 'Mavs',
points: 30,
rebounds: 8 }
{ _id: ObjectId("61f952c167f1c64a1afb203a"),
team: 'Spurs',
points: 30,
rebounds: 12 }
请注意,文档按增加“points”字段(从最小到最大)然后按增加“rebounds”字段(从最小到最大)排序。
示例2:MongoDB中按多个字段排序(降序)
我们可以使用以下代码对team集合中的文档进行排序,首先通过减少“points”,然后减少“bounces”:
db.teams.find().sort( { " points ": -1, " rebounds ": -1 } )
该查询返回以下结果:
{ _id: ObjectId("61f952c167f1c64a1afb203a"),
team: 'Spurs',
points: 30,
rebounds: 12 }
{ _id: ObjectId("61f952c167f1c64a1afb2039"),
team: 'Mavs',
points: 30,
rebounds: 8 }
{ _id: ObjectId("61f952c167f1c64a1afb203d"),
team: 'Cavs',
points: 25,
rebounds: 9 }
{ _id: ObjectId("61f952c167f1c64a1afb203c"),
team: 'Warriors',
points: 25,
rebounds: 5 }
{ _id: ObjectId("61f952c167f1c64a1afb203b"),
team: 'Rockets',
points: 20,
rebounds: 7 }
请注意,文档按递减的“points”字段(从最大到最小)排序,然后按递减的“rebounds”字段(从最大到最小)排序。
注意:您可以在此处找到排序函数的完整文档。
其他资源
以下教程解释了如何在 MongoDB 中执行其他常见操作: