MongoDB 按两个字段求和排序?
若要按照两个字段求和进行排序,可以使用集合框架。我们首先创建一个包含文档的集合
> db.orderByTwoFieldsDemo.insertOne({"Value1":10,"Value2":35}); { "acknowledged" : true, "insertedId" : ObjectId("5ca285576304881c5ce84baa") } > db.orderByTwoFieldsDemo.insertOne({"Value1":12,"Value2":5}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2855f6304881c5ce84bab") } > db.orderByTwoFieldsDemo.insertOne({"Value1":55,"Value2":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ca285686304881c5ce84bac") }
以下是使用 find() 方法从集合中显示所有文档的查询
> db.orderByTwoFieldsDemo.find().pretty();
这将生成以下输出
{ "_id" : ObjectId("5ca285576304881c5ce84baa"), "Value1" : 10, "Value2" : 35 } { "_id" : ObjectId("5ca2855f6304881c5ce84bab"), "Value1" : 12, "Value2" : 5 } { "_id" : ObjectId("5ca285686304881c5ce84bac"), "Value1" : 55, "Value2" : 65 }
案例 1: 以下是按两个字段求和并按升序获取结果的查询
> db.orderByTwoFieldsDemo.aggregate( ... [ ... {$project:{Value1:1, Value2:1, orderBySumValue:{$add: ["$Value1", "$Value2"]}}}, ... {$sort:{orderBySumValue:1}}] ... );
这将生成以下输出
{ "_id" : ObjectId("5ca2855f6304881c5ce84bab"), "Value1" : 12, "Value2" : 5, "orderBySumValue" : 17 } { "_id" : ObjectId("5ca285576304881c5ce84baa"), "Value1" : 10, "Value2" : 35, "orderBySumValue" : 45 } { "_id" : ObjectId("5ca285686304881c5ce84bac"), "Value1" : 55, "Value2" : 65, "orderBySumValue" : 120 }
案例 2: 以下是按两个字段求和并按降序获取结果的查询
> db.orderByTwoFieldsDemo.aggregate( [ {$project:{Value1:1, Value2:1, orderBySumValue:{$add: ["$Value1", "$Value2"]}}}, {$sort:{orderBySumValue:-1}}] );
这将生成以下输出
{ "_id" : ObjectId("5ca285686304881c5ce84bac"), "Value1" : 55, "Value2" : 65, "orderBySumValue" : 120 } { "_id" : ObjectId("5ca285576304881c5ce84baa"), "Value1" : 10, "Value2" : 35, "orderBySumValue" : 45 } { "_id" : ObjectId("5ca2855f6304881c5ce84bab"), "Value1" : 12, "Value2" : 5, "orderBySumValue" : 17 }
广告