要按差异排序,请在MongoDB中使用aggregate()。让我们创建一个包含文档的集合-
> db.demo155.insertOne({"Scores":[{"Value":45},{"Value":50}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e354584fdf09dd6d08539e3") } > db.demo155.insertOne({"Scores":[{"Value":60},{"Value":10}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e35458efdf09dd6d08539e4") } > db.demo155.insertOne({"Scores":[{"Value":100},{"Value":95}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e354599fdf09dd6d08539e5") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo155.find();
这将产生以下输出-
{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ] } { "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ] } { "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ] }
以下是使用MongoDB按数组内容的差异进行排序的查询-
> db.demo155.aggregate([ ... { "$match": { "Scores.1": { "$exists": true } } }, ... { "$project": { ... "Scores": "$Scores", ... "sub": { ... "$let": { ... "vars": { ... "f": { "$arrayElemAt": [ "$Scores", -2 ] }, ... "l": { "$arrayElemAt": [ "$Scores", -1 ] } ... }, ... "in": { "$subtract": [ "$$l.Value", "$$f.Value" ] } ... } ... } ... }}, ... { "$sort": { "sub": -1 } } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ], "sub" : 5 } { "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ], "sub" : -5 } { "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ], "sub" : -50 }