Reputation: 23302
In a Mongo Aggregation example I've encountered the expression $$this
, but cannot find a reference to it in the MongoDB documentation (not even in the documentation about aggregation variables)
Here is the sample data:
{ "_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 ] }
Here is the code
Here is the code I'm looking at:
db.test.aggregate([
{$match:{actions:{$all:[6,3,8]}}},
{$project:{actions638:{$map:{
input:{$range:[0,{$subtract:[{$size:"$actions"},2]}]},
in:{$slice:["$actions","$$this",3]}
}}}}
])
and here is the output
{ "_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 ] ] }
Upvotes: 9
Views: 8355
Reputation: 23302
$$this
refers to the current item inside the array that is being processed by the $map
function.
An alternative is to use the as
property so that instead of referring to $$this
you refer to the name you provided in the as
. For example (from the docs)
db.grades.aggregate(
[
{ $project:
{ adjustedGrades:
{
$map:
{
input: "$quizzes",
as: "grade",
in: { $add: [ "$$grade", 2 ] }
}
}
}
}
]
)
Upvotes: 10