MongoDB展开多个数组

cor*_*rry 9 arrays mongodb bson mongodb-query

在mongodb中有以下结构的文档:

{
    "_id" : ObjectId("52d017d4b60fb046cdaf4851"),
    "dates" : [
        1399518702000,
        1399126333000,
        1399209192000,
        1399027545000
    ],
    "dress_number" : "4",
    "name" : "J. Evans",
    "numbers" : [
        "5982",
        "5983",
        "5984",
        "5985"
    ]
}
Run Code Online (Sandbox Code Playgroud)

是否可以从多个数组中展开数据并仅从数组中获取成对元素:

{
    "dates": "1399518702000",
    "numbers": "5982"
},
{
    "dates": "1399126333000",
    "numbers": "5983"
},
{
    "dates": "1399209192000",
    "numbers": "5984"
},
{
    "dates": "1399027545000",
    "numbers": "5985"
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*omG 11

从版本3.2开始,您可以$unwind在两个阵列,$cmp索引和$match仅相同的索引上执行此操作.

如果您只有示例文档,此解决方案将填充您编写的内容.如果你有更多文档我不知道你期望在输出中得到什么,但它可以通过文档的_id分组来解决.

db.test.aggregate([
    {
        $unwind: {
            path: '$dates',
            includeArrayIndex: 'dates_index',
        }
    },
    {
        $unwind: {
            path: '$numbers',
            includeArrayIndex: 'numbers_index',
        }
    },
    {
        $project: {
            dates: 1,
            numbers: 1,
            compare: {
                $cmp: ['$dates_index', '$numbers_index']
            }
        }
    },
    {
        $match: {
            compare: 0
        }
    },
    {
        $project: {
            _id: 0,
            dates: 1,
            numbers: 1
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

  • @corry 你是怎么理解的?您可以根据需要放松身心。问题是每个元素都将成为一个文档,因此对于许多展开,结果将是巨大的 db。这将很难处理,他们的问题是你想用它们做什么。 (2认同)