MongoDB从文档中提取子数组

时间:2016-12-19 15:58:49

标签: mongodb mongodb-query aggregation-framework

如何从此文档集合中传递

/* 1 */
{
    "F" : [ 
        {
            "n" : "test1",
            "v" : "value1"
        }, 
        {
            "n" : "test2",
            "v" : "value2"
        }
    ],
    "POR" : [ 
        {
            "n" : "1test1",
            "v" : "1value1"
        }, 
        {
            "n" : "1test2",
            "v" : "1value2"
        }, 
        {
            "n" : "1test3",
            "v" : "1value3"
        }
    ]
}

/* 2 */
{
    "F" : [ 
        {
            "n" : "2test1",
            "v" : "2value1"
        }, 
        {
            "n" : "2test2",
            "v" : "2value2"
        }
    ],
    "POR" : [ 
        {
            "n" : "2test1",
            "v" : "2value1"
        }, 
        {
            "n" : "2test2",
            "v" : "2value2"
        }
    ]
}

/* 3 */
{
    "F" : [ 
        {
            "n" : "3test1",
            "v" : "3value1"
        }, 
        {
            "n" : "3test2",
            "v" : "3value2"
        }
    ],
    "POR" : [ 
        {
            "n" : "3test1",
            "v" : "3value1"
        }
    ]
}

到此:

{
    "ITEMS": [
        { "n": "2test1", "v": "2value1" },
        { "n": "2test2", "v": "2value2" },
        { "n": "1test1", "v": "1value1" },
        { "n": "1test2", "v": "1value2" },
        { "n": "1test3", "v": "1value3" },
        { "n": "3test1", "v": "3value1" }
    ]
}

我想从多个文档中提取子数组元素,但我找不到方法/方法。

尝试了第一种方法:

db.test.aggregate( [ { $unwind : "$POR" } ] ).pretty();

1 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求:

> db.uwnd.aggregate([
     {$unwind:"$F"},
     {$unwind:"$POR"},
     {$group:{_id:null,items:{$addToSet:"$F",$addToSet:"$POR"}}}
   ]).pretty()

鉴于上述数据,这将返回以下文件:

{
        "_id" : null,
        "items" : [
                {
                        "n" : "1test3",
                        "v" : "1value3"
                },
                {
                        "n" : "1test1",
                        "v" : "1value1"
                },
                {
                        "n" : "1test2",
                        "v" : "1value2"
                },
                {
                        "n" : "2test1",
                        "v" : "2value1"
                },
                {
                        "n" : "2test2",
                        "v" : "2value2"
                },
                {
                        "n" : "3test1",
                        "v" : "3value1"
                }
        ]
}

因此,查询展开两个数组,然后对数据进行分组,将条目添加到"F""POR"对象的新项目数组