MongoDB 展开多个数组 [英] MongoDB unwind multiple arrays

查看:32
本文介绍了MongoDB 展开多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In mongodb there are documents in the following structure:

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

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

Is it possible unwind data from multiple arrays and get only paired elements from arrays:

{
    "dates": "1399518702000",
    "numbers": "5982"
},
{
    "dates": "1399126333000",
    "numbers": "5983"
},
{
    "dates": "1399209192000",
    "numbers": "5984"
},
{
    "dates": "1399027545000",
    "numbers": "5985"
}

推荐答案

从 3.2 版开始,您可以在两个数组上使用 $unwind 来实现,$cmp索引,并且 $match 只是相等的索引.

From version 3.2 you can do it with $unwind on both of the arrays, $cmp the indexes, and $match only the equal indexes.

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

This solution will populate what you wrote in case you have only the example document. If you have more documents I don't know what you expect to get in the output, but it's solvable by grouping by _id of the document.

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
        }
    }
])

这篇关于MongoDB 展开多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆