在 MongoDB 的 "$group" 操作中排序并仅获取前两个字段


让我们创建一个带有文档的集合 -

> db.demo576.insertOne({id:101,Name:"Chris",Marks:45}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c3b581e9acd78b427fa")
}
> db.demo576.insertOne({id:101,Name:"John",Marks:55}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c43581e9acd78b427fb")
}
> db.demo576.insertOne({id:101,Name:"John",Marks:65}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c47581e9acd78b427fc")
}
> db.demo576.insertOne({id:102,Name:"David",Marks:37}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c55581e9acd78b427fd")
}
> db.demo576.insertOne({id:102,Name:"David",Marks:75}){
   "acknowledged" : true, "insertedId" : ObjectId("5e916c5e581e9acd78b427fe")
}

使用 find() 方法显示集合中的所有文档 -

> db.demo576.find();

这将产生以下输出 -

{ "_id" : ObjectId("5e916c3b581e9acd78b427fa"), "id" : 101, "Name" : "Chris", "Marks" : 45 }
{ "_id" : ObjectId("5e916c43581e9acd78b427fb"), "id" : 101, "Name" : "John", "Marks" : 55 }
{ "_id" : ObjectId("5e916c47581e9acd78b427fc"), "id" : 101, "Name" : "John", "Marks" : 65 }
{ "_id" : ObjectId("5e916c55581e9acd78b427fd"), "id" : 102, "Name" : "David", "Marks" : 37 }
{ "_id" : ObjectId("5e916c5e581e9acd78b427fe"), "id" : 102, "Name" : "David", "Marks" : 75 }

以下是查询,用于在“$group”操作中排序并仅获取前两个字段 -

> var query = [
...    {
...       "$sort": { "Marks": 1 }
...    },
...    {
...       "$group": {
...          "_id": "$id",
...          "out": { "$first": "$$ROOT" }
...       }
...    },
...    {
...       "$project": {
...          "_id": "$out._id",
...          "id": "$out.id",
...          "Name": "$out.Name",
...          "MinMarks": "$out.Marks"
...       }
...    }
... ]
> db.demo576.aggregate(query);

这将产生以下输出 -

{ "_id" : ObjectId("5e916c3b581e9acd78b427fa"), "id" : 101, "Name" : "Chris", "MinMarks" : 45 }
{ "_id" : ObjectId("5e916c55581e9acd78b427fd"), "id" : 102, "Name" : "David", "MinMarks" : 37 }

更新于:2020 年 5 月 15 日

274 次浏览

职业生涯瞬间启动

完成课程,获得认证

开始学习
广告