在单个MongoDB查询中一起执行分组和区分
为此,只需使用MongoDB$group。首先让我们创建一个包含文档的集合-
> db.demo16.insertOne({
... "StudentName" : "Chris",
... "StudentSection" : "A",
... "StudentAge" : 23,
... "StudentMarks" : 47
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827455d0fc6657d21f07")
}
> db.demo16.insertOne({
... "StudentName" : "Bob",
... "StudentSection" : "B",
... "StudentAge" : 21,
... "StudentMarks" : 85
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827555d0fc6657d21f08")
}
> db.demo16.insertOne( {
... "StudentName" : "Carol",
... "StudentSection" : "A",
... "StudentAge" : 26,
... "StudentMarks" : 97
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e13827655d0fc6657d21f09")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.demo16.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5e13827455d0fc6657d21f07"),
"StudentName" : "Chris",
"StudentSection" : "A",
"StudentAge" : 23,
"StudentMarks" : 47
}
{
"_id" : ObjectId("5e13827555d0fc6657d21f08"),
"StudentName" : "Bob",
"StudentSection" : "B",
"StudentAge" : 21,
"StudentMarks" : 85
}
{
"_id" : ObjectId("5e13827655d0fc6657d21f09"),
"StudentName" : "Carol",
"StudentSection" : "A",
"StudentAge" : 26,
"StudentMarks" : 97
}以下是一起实施分组和不同操作的查询-
> db.demo16.aggregate([{
... $group : {
... _id : null,
... StudentName : { $addToSet : "$StudentName" },
... StudentSection : { $addToSet : "$StudentSection" },
... StudentMinimumAge : { $min : "$StudentAge" },
... StudentMaximumAge : { $max : "$StudentAge" },
... StudentMinimumMarks: { $min : "$StudentMarks" },
... StudentMaximumMarks : { $max : "$StudentMarks" }
... }
... }]).pretty();这将产生以下输出-
{
"_id" : null,
"StudentName" : [
"Carol",
"Bob",
"Chris"
],
"StudentSection" : [
"B",
"A"
],
"StudentMinimumAge" : 21,
"StudentMaximumAge" : 26,
"StudentMinimumMarks" : 47,
"StudentMaximumMarks" : 97
}热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便