在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 }