为此,请使用aggregate()和$group。要获得最小值和最大值,请使用$min和$max。
让我们创建一个包含文档的集合-
> db.demo167.insertOne({"Score":60}); { "acknowledged" : true, "insertedId" : ObjectId("5e3693a79e4f06af551997d1") } > db.demo167.insertOne({"Score":80}); { "acknowledged" : true, "insertedId" : ObjectId("5e3693ab9e4f06af551997d2") } > db.demo167.insertOne({"Score":60}); { "acknowledged" : true, "insertedId" : ObjectId("5e3693ad9e4f06af551997d3") } > db.demo167.insertOne({"Score":90}); { "acknowledged" : true, "insertedId" : ObjectId("5e3693b09e4f06af551997d4") } > db.demo167.insertOne({"Score":89}); { "acknowledged" : true, "insertedId" : ObjectId("5e3693b69e4f06af551997d5") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo167.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3693a79e4f06af551997d1"), "Score" : 60 } { "_id" : ObjectId("5e3693ab9e4f06af551997d2"), "Score" : 80 } { "_id" : ObjectId("5e3693ad9e4f06af551997d3"), "Score" : 60 } { "_id" : ObjectId("5e3693b09e4f06af551997d4"), "Score" : 90 } { "_id" : ObjectId("5e3693b69e4f06af551997d5"), "Score" : 89 }
以下是获取最小值和最大值的查询-
> var d = [ ... { ... "$group": { ... "_id": "id", ... "MinimumValue": { "$min": "$Score" }, ... "MaximumValue": { "$max": "$Score" } ... } ... } ... ] > db.demo167.aggregate(d);
这将产生以下输出-
{ "_id" : "id", "MinimumValue" : 60, "MaximumValue" : 90 }