Cod*_*ein 9 mongodb aggregation-framework
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 ] }
Run Code Online (Sandbox Code Playgroud)
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]}
}}}}
])
Run Code Online (Sandbox Code Playgroud)
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 ] ] }
Run Code Online (Sandbox Code Playgroud)
Cod*_*ein 10
$$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 ] }
}
}
}
}
]
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7333 次 |
| 最近记录: |