您可以为此使用聚合框架。首先让我们创建一个包含文档的集合-
> db.summingSubDocumentDemo.insertOne( ... { "_id" :101, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 2000 } } }); { "acknowledged" : true, "insertedId" : 101 } > db.summingSubDocumentDemo.insertOne( { "_id" :102, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 3000 } } }); { "acknowledged" : true, "insertedId" : 102 } > db.summingSubDocumentDemo.insertOne( { "_id" :103, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 5000 } } }); { "acknowledged" : true, "insertedId" : 103 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.summingSubDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 2000 } } } { "_id" : 102, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 3000 } } } { "_id" : 103, "CustomerDetails" : { "CustomerPurchase" : { "CustomerPurchaseAmount" : 5000 } } }
这是汇总MongoDB子文档字段的查询-
> db.summingSubDocumentDemo.aggregate({$group : {_id: "", ... totalAmount : {$sum: "$CustomerDetails.CustomerPurchase.CustomerPurchaseAmount"}}}, ... {$project: {_id: 0, totalAmount: 1}});
这将产生以下输出-
{ "totalAmount" : 10000 }