要按两个字段求和,可以使用聚合框架。首先让我们创建一个包含文档的集合
> 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 }