包含或不包含子数组记录的聚合记录

时间:2016-02-26 12:47:10

标签: mongodb aggregation-framework

我无法成功提取所有主要记录并最终提取数组。我只提取“属性”计数>的主记录字段。 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“等...

祝你好运

2 个答案:

答案 0 :(得分:0)

$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"}
                }
        } } );

答案 1 :(得分:0)

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