1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
// Tests that JavaScript functions stored in system.js are loaded on a per-expression basis.
// @tags: [
// assumes_unsharded_collection,
// requires_non_retryable_writes,
// sbe_incompatible,
// ]
(function() {
"use strict";
const testDB = db.getSiblingDB('system_js_access');
const coll = testDB.system_js_access;
coll.drop();
testDB.system.js.deleteMany({});
assert.commandWorked(coll.insert([
{"name": "Alice", "age": 68},
{"name": "Bowen", "age": 20},
{"name": "Carlos", "age": 24},
{"name": "Daniel", "age": 47},
{"name": "Eric", "age": 14},
{"name": "France", "age": 1}
]));
// Store JS function in database.
assert.commandWorked(testDB.system.js.insert({
_id: "isAdult",
value: function(age) {
return age >= 21;
}
}));
// $where can access stored functions.
assert.commandWorked(
testDB.runCommand({find: coll.getName(), filter: {$where: "isAdult(this.age)"}}));
// $function cannot access stored functions.
assert.commandFailedWithCode(testDB.runCommand({
aggregate: coll.getName(),
pipeline:
[{$addFields: {isAdult: {$function: {body: "isAdult(age)", args: ["$age"], lang: "js"}}}}],
cursor: {}
}),
ErrorCodes.JSInterpreterFailure);
// The same function specified in-line can be executed by $function.
assert.commandWorked(testDB.runCommand({
aggregate: coll.getName(),
pipeline: [{
$match: {
$expr: {
$function: {
body: function(age) {
return age >= 21;
},
args: ["$age"],
lang: "js"
}
}
}
}],
cursor: {}
}));
// Mixed queries with both $where and $function should fail, because $where has to provide system.js
// to user code, and $function has to not provide it.
assert.commandFailedWithCode(testDB.runCommand({
find: coll.getName(),
filter: {
$and: [
{
$expr: {
$function: {
body: function(age) {
return age >= 21;
},
args: ["$age"],
lang: "js"
}
}
},
{$where: "isAdult(this.age)"}
]
}
}),
4649200);
// Queries with both $function and $accumulator should succeed, because both of these operators
// provide system.js to user code.
assert.commandWorked(testDB.runCommand({
aggregate: coll.getName(),
pipeline: [
{
$match: {
$expr: {
$function: {
body: function(age) {
return age >= 21;
},
args: ["$age"],
lang: "js"
}
}
}
},
{
$group: {
_id: "$name",
age: {
$accumulator: {
init: function() {
return 0;
},
accumulate: function(state, value) {
return state + value;
},
accumulateArgs: ["$age"],
merge: function(state1, state2) {
return state1 + state2;
},
lang: 'js',
}
}
}
}
],
cursor: {}
}));
}());
|