MongoDB的数据存储使用嵌套结构非常普遍,它通过嵌套子文档,实现一对多的关联关系。但嵌套结构分组进行子文档去重数据计算时,常需要将嵌套结构提升为扁平结构,再通过 $group 聚集运算来实现。
下面以集合 fund 为例说明,按 id 分组获取 shares、trade 子文档下的不重复 fundcode 数量。具体数据如下:
{
"id" : 1, "shares" : [ { "fundcode" : "000001", "lastshares" : 1230.2, "agencyno" : "260", "netno" : "260" }, { "fundcode" : "000002", "lastshares" : 213124, "agencyno" : "469", "netno" : "001" }, { "fundcode" : "000001", "lastshares" : 10000.8, "agencyno" : "469", "netno" : "002" } ], "trade" : [ { "fundcode" : "000001", "c_date" : "20180412", |
"agencyno" : "260", "netno" : "260","bk_tradetype" : "122", "confirmbalance" : 1230.2, }, { "f |