使用聚合管道在 MongoDB 中提取记录
MongoDB 聚合管道具有阶段。每个阶段在文档通过管道时都会转换这些文档。
我们首先使用文档创建一个集合 -
> db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[65,78,36,90]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5f4903d395bdc2134712") } > db.demo218.insertOne({"Name":"David","Branch":"ME",Marks:[56,45,42,51]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5f6203d395bdc2134713") } > db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[78,65,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5f6c03d395bdc2134714") }
使用 find() 方法从集合显示所有文档 -
> db.demo218.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e3e5f4903d395bdc2134712"), "Name" : "Chris", "Branch" : "CS", "Marks" : [ 65, 78, 36, 90 ] } { "_id" : ObjectId("5e3e5f6203d395bdc2134713"), "Name" : "David", "Branch" : "ME", "Marks" : [ 56, 45, 42, 51 ] } { "_id" : ObjectId("5e3e5f6c03d395bdc2134714"), "Name" : "Chris", "Branch" : "CS", "Marks" : [ 78, 65, 89 ] }
以下是聚合管道的查询 -
> db.demo218.aggregate([ ... { "$unwind": "$Marks" }, ... { "$match": ... { ... "Branch": "CS", ... "Marks": { "$gt": 88 } ... } ... }, ... { "$group": ... { ... "_id": "$_id", ... "Branch": { "$first": "$Branch" }, ... "Marks": { "$first": "$Marks" } ... } ... } ...])
这将产生以下输出 -
{ "_id" : ObjectId("5e3e5f6c03d395bdc2134714"), "Branch" : "CS", "Marks" : 89 } { "_id" : ObjectId("5e3e5f4903d395bdc2134712"), "Branch" : "CS", "Marks" : 90 }
广告