将$max和$min运算符与聚合框架一起使用以获取最大值和最小值。首先让我们创建一个包含文档的集合-
> db.maxAndMinDemo.insertOne({"Value":98}); { "acknowledged" : true, "insertedId" : ObjectId("5cd698a357806ebf1256f129") } > db.maxAndMinDemo.insertOne({"Value":97}); { "acknowledged" : true, "insertedId" : ObjectId("5cd698af57806ebf1256f12a") } > db.maxAndMinDemo.insertOne({"Value":69}); { "acknowledged" : true, "insertedId" : ObjectId("5cd698b357806ebf1256f12b") } > db.maxAndMinDemo.insertOne({"Value":96}); { "acknowledged" : true, "insertedId" : ObjectId("5cd698b657806ebf1256f12c") } > db.maxAndMinDemo.insertOne({"Value":99}); { "acknowledged" : true, "insertedId" : ObjectId("5cd698b957806ebf1256f12d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.maxAndMinDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd698a357806ebf1256f129"), "Value" : 98 } { "_id" : ObjectId("5cd698af57806ebf1256f12a"), "Value" : 97 } { "_id" : ObjectId("5cd698b357806ebf1256f12b"), "Value" : 69 } { "_id" : ObjectId("5cd698b657806ebf1256f12c"), "Value" : 96 } { "_id" : ObjectId("5cd698b957806ebf1256f12d"), "Value" : 99 }
以下是对MongoDB中的max和min的查询-
> db.maxAndMinDemo.aggregate([ { "$group": { "_id": null, "MaximumValue": { "$max": "$Value" }, "MinimumValue": { "$min": "$Value" } }} ]);
这将产生以下输出-
{ "_id" : null, "MaximumValue" : 99, "MinimumValue" : 69 }