【问题标题】:aggregate records with or without sub array records聚合记录有或没有子数组记录
【发布时间】:2016-02-26 12:47:09
【问题描述】:

我无法成功提取所有主要记录并最终提取数组。我只提取“属性”计数 > 0 的主要记录字段。

数据样本为:

docs = [ 
    { docId : "1", fieldDoc1: "value", fieldDoc2: "value", attributes: [ { attrId: "1.1", fieldAttr1: "value" }, { attrId: "1.2", fieldAttr1: "value" }] },
    { docId : "2", fieldDoc1: "value", fieldDoc2: "value", attributes: [ { attrId: "2.1", fieldAttr1: "value" }] },
    { docId : "3", fieldDoc1: "value", fieldDoc2: "value", attributes: [ ] }
    ];

db.table.aggregate ( 
    { $match: { criterias on main part fields }, 
    { $unwind: "attributes" }, 
    { $match: { criteria on attributes fields },
    { $group : { 
            _id : "$docId", 
            "docs": { 
                "$push": { 
                    "_id": "$docId", 
                    "fieldDoc1": "$fieldDoc1", 
                    "fieldDoc2": "$fieldDoc2",
                    "attributes": "$attributes"}
                }
        } } );

例如,为了提取所有记录,我尝试:

db.table.aggregate ( 
        { $unwind: "attributes" }, 
        { $group : { 
                _id : "$docId", 
                "docs": { 
                    "$push": { 
                        "_id": "$docId", 
                        "fieldDoc1": "$fieldDoc1", 
                        "fieldDoc2": "$fieldDoc2",
                        "attributes": "$attributes"}
                    }
            } } );

我只得到 docId:"1" 和 docId:"2" 及其属性。 没有属性的docId:"3"不返回。

1) 那么如何获取所有对应的记录,有无属性;

2) 如何获取主要部分的所有字段,而不是逐字逐句地枚举它们(fieldDoc1:"$fieldDoc1", fieldDoc2":"$fieldDoc2", etc...

最好的问候

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    $exists: true 将匹配那些存在该字段的文档,即使它为 null 或空。

    db.table.aggregate (
        { $match: { attributes : { $exists: true }} }, 
        { $unwind: "attributes" }, 
        { $group : { 
                _id : "$docId", 
                "docs": { 
                    "$push": { 
                        "_id": "$docId", 
                        "fieldDoc1": "$fieldDoc1", 
                        "fieldDoc2": "$fieldDoc2",
                        "attributes": "$attributes"}
                    }
            } } );
    

    【讨论】:

    • 呃,这对我不起作用。我认为该解决方案由 mongodb 3.2 提供,带有选项:$unwind:{path: ,preserveNullAndEmptyArrays: true}。但我无法更新我的框架。
    【解决方案2】:

    我找到的最佳答案是将 mongo 更新到 3.2 版,然后使用 $unwind:{path: ,preserveNullAndEmptyArrays: true}。这非常有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多