这在MongoDB聚合中意味着什么?

时间:2018-06-14 18:11:43

标签: mongodb aggregation-framework

a Mongo Aggregation example I've encountered表达式$$this中,但在MongoDB文档中找不到对它的引用(甚至没有关于aggregation variables的文档)

以下是示例数据:

{ "_id" : 1, "actions" : [ 2, 6, 3, 8, 5, 3 ] }
{ "_id" : 2, "actions" : [ 6, 4, 2, 8, 4, 3 ] }
{ "_id" : 3, "actions" : [ 6, 4, 6, 4, 3 ] }
{ "_id" : 4, "actions" : [ 6, 8, 3 ] }
{ "_id" : 5, "actions" : [ 6, 8 ] }
{ "_id" : 6, "actions" : [ 6, 3, 11, 8, 3 ] }
{ "_id" : 7, "actions" : [ 6, 3, 8 ] }

这是代码

以下是我正在查看的代码:

db.test.aggregate([
    {$match:{actions:{$all:[6,3,8]}}},
    {$project:{actions638:{$map:{
       input:{$range:[0,{$subtract:[{$size:"$actions"},2]}]},
       in:{$slice:["$actions","$$this",3]}
    }}}}
])

这是输出

{ "_id" : 1, "actions638" : [ [ 2, 6, 3 ], [ 6, 3, 8 ], [ 3, 8, 5 ], [ 8, 5, 3 ] ] }
{ "_id" : 2, "actions638" : [ [ 6, 4, 2 ], [ 4, 2, 8 ], [ 2, 8, 4 ], [ 8, 4, 3 ] ] }
{ "_id" : 4, "actions638" : [ [ 6, 8, 3 ] ] }
{ "_id" : 6, "actions638" : [ [ 6, 3, 11 ], [ 3, 11, 8 ], [ 11, 8, 3 ] ] }
{ "_id" : 7, "actions638" : [ [ 6, 3, 8 ] ] }

1 个答案:

答案 0 :(得分:0)

$$this指的是$map函数正在处理的数组中的当前项。

另一种方法是使用as属性,这样您就可以引用$$this中提供的名称,而不是引用as。例如(from the docs

db.grades.aggregate(
   [
      { $project:
         { adjustedGrades:
            {
              $map:
                 {
                   input: "$quizzes",
                   as: "grade",
                   in: { $add: [ "$$grade", 2 ] }
                 }
            }
         }
      }
   ]
)