MongoDB unwind multiple arrays

后端 未结 1 1535
北恋
北恋 2020-12-18 22:45

In mongodb there are documents in the following structure:

{
    \"_id\" : ObjectId(\"52d017d4b60fb046cdaf4851\"),
    \"dates\" : [
        1399518702000,
          


        
相关标签:
1条回答
  • 2020-12-18 23:05

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

    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
            }
        }
    ])
    
    0 讨论(0)
提交回复
热议问题