对。你可以用
$subtract
然后用你的数据计算差异
$sort
在mongo shell中看起来是这样的
Enterprise repl2:PRIMARY> db.wang.aggregate([{ $project: { a: 1, b:1, differ: { $subtract: [ "$a", "$b" ] } } },{$sort :{differ:-1}} ] )
{ "_id" : ObjectId("5d494045fd02abc31f622366"), "a" : 100, "b" : 30, "differ" : 70 }
{ "_id" : ObjectId("5d494062fd02abc31f622368"), "a" : 13, "b" : 7, "differ" : 6 }
{ "_id" : ObjectId("5d49406afd02abc31f622369"), "a" : 13, "b" : 9, "differ" : 4 }
{ "_id" : ObjectId("5d494058fd02abc31f622367"), "a" : 10, "b" : 7, "differ" : 3 }
MongoDB Enterprise repl2:PRIMARY> db.wang.find()
{ "_id" : ObjectId("5d494045fd02abc31f622366"), "a" : 100, "b" : 30 }
{ "_id" : ObjectId("5d494058fd02abc31f622367"), "a" : 10, "b" : 7 }
{ "_id" : ObjectId("5d494062fd02abc31f622368"), "a" : 13, "b" : 7 }
{ "_id" : ObjectId("5d49406afd02abc31f622369"), "a" : 13, "b" : 9 }
MongoDB Enterprise repl2:PRIMARY>
稍后我会给你一个java演示
编辑
AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(Aggregates.project(fields(include("a", "b"),
new BasicDBObject("differ",new BasicDBObject("$subtract",Arrays.asList("$a","$b"))))),
Aggregates.sort(new BasicDBObject("differ",-1)),
Aggregates.project(fields(include("a","b")))));
MongoCursor<Document> iterator = aggregate.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
为错误编辑
在字段前面加上
$
使用时
Subtract
.
Subtract.valueOf("$originalPrice")
.subtract("$discountPrice"))
.as("diff");
你最好把你的
spring-data-mongodb
版本