MongoDB 中嵌套文档的聚合?
对于 MongoDB 中的聚合,使用 aggregate()。让我们使用文档创建一个 collection−
> db.demo199.insertOne( ... { ... "details1":{ ... "details2":{ ... "details3":{ ... "Name":"Chris", ... "details4":{ ... "details5":{ ... "v1":10, ... "v2":20, ... "v3":30 ... } ... } ... }}}} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3c24aa03d395bdc21346e2") } > > db.demo199.insertOne( ... { ... "details1":{ ... "details2":{ ... "details3":{ ... "Name":"Chris", ... "details4":{ ... "details5":{ ... "v1":30, ... "v2":40, ... "v3":50 ... } ... } ... }}}} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3c24ab03d395bdc21346e3") }
使用 find() 方法显示 collection 中的所有文档−
> db.demo199.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3c24aa03d395bdc21346e2"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 10, "v2" : 20, "v3" : 30 } } } } } } { "_id" : ObjectId("5e3c24ab03d395bdc21346e3"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 30, "v2" : 40, "v3" : 50 } } } } } }
以下是 MongoDB 针对嵌套文档进行聚合的查询−
> var out = [ ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$group": { ... "_id": "$details1.details2._id", ... "v1": { "$sum": "$details1.details2.details3.details4.details5.v1" }, ... "v2": { "$sum": "$details1.details2.details3.details4.details5.v2" }, ... "v3": { "$sum": "$details1.details2.details3.details4.details5.v3" }, ... } ... } ...] > result = db.demo199.aggregate(out);
这将产生以下输出 −
{ "_id" : null, "v1" : 40, "v2" : 60, "v3" : 80 }
广告