在MongoDB聚合中加入两个数组?

时间:2017-02-16 09:04:25

标签: mongodb

聚合产生了两个数组:$array1$array2

    $array1 = [{ key1_1: 0,
                 key1_2: 1,
                 key1_3: 2 
               },
               { key1_1: 0,
                 key1_2: 1,
                 key1_3: 2 
               }]

    $array2 = [{ key2_1: 0,
                 key2_2: 1 
               }, 
               { key2_1: 0,
                 key2_2: 1 
               }]

我想完全加入他们。

如果我这样做:

{ $project: { 'output': { $concatArrays: [ '$array1', '$array2' ] } }

结果将是:

output: [{  key1_1: 0,
            key1_2: 1,
            key1_3: 2
          },
          { key2_1: 0,
            key2_2: 1 
          },
          { key1_1: 0,
            key1_2: 1,
            key1_3: 2
          },
          { key2_1: 0,
            key2_2: 1
          }]

虽然我更喜欢这个:

output: [{  key1_1: 0, 
            key1_2: 1,
            key1_3: 2,
            key2_1: 0,
            key2_2: 1
          },
          { key1_1: 0,
            key1_2: 1,
            key1_3: 2,
            key2_1: 0,
            key2_2: 1
          }]

我想这只能由$project来实现,但是怎么做?

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,这不是我想要的,但它已经足够好了。

在聚合中,首先是

<ComVisible(True)>
<ProgId("TESTCOM.Class1")>
<ComClass("E26FE8A0-8AC7-4824-9776-30ECDD473AA3", "79571A9D-2345-48D9-8F86-7F6761A97DBA")>
Public Class Class1
    'Inherits ServicedComponent
    'Implements IClass1

    Public Sub New()
        ' needed for COM
    End Sub

    Private Const LogMessageFormat As String = "[{0:s}] Input: {1}, {2}" + vbCrLf

    Public Function Triple(csinput As String, nInput As Integer) As Integer 'Implements IClass1.Triple
        IO.File.AppendAllText("C:\TestCOM.Class1_Triple.log", 
                              String.Format(LogMessageFormat, Date.Now, if(csinput isnot Nothing, csinput, "**NULL**"), nInput))
        Return 97
    End Function
End Class

然后进行分组:

{ $unwind: '$array1' },
{ $unwind: '$array2' },

结果将是:

{ $group: { _id: '$_id',
           arrays: { $push: { 
                              array1: '$array1',
                              array2: '$array2' 
                            }
                   }
           }
 },

答案 1 :(得分:0)

不聚合可能更容易吗?:

> var a =[];
> var array1 = [{ key1_1: 0,                  key1_2: 1,                  key1_3: 2                 },                { key1_1: 0,                  key1_2: 1,                  key1_3: 2                 }];
> var array2 = [{ key2_1: 0,                  key2_2: 1                 },                 { key2_1: 0,                  key2_2: 1                 }];
> array1.forEach(function(o,i){a.push(Object.assign(array1[i],array2[i]));});
> printjson(a);
[
        {
                "key1_1" : 0,
                "key1_2" : 1,
                "key1_3" : 2,
                "key2_1" : 0,
                "key2_2" : 1
        },
        {
                "key1_1" : 0,
                "key1_2" : 1,
                "key1_3" : 2,
                "key2_1" : 0,
                "key2_2" : 1
        }
]