In a Typesctipt code, I would like to use a varible value in an aggregation pipeline in MongoDB; the problem is that the “keyToCheck” field is a variable that is set by the Typescript code and, therefore, can change based by many conditions.
Is there a way to expand the variable “keyToCheck”?
I have tried $$keyToCheck
, $keyToCheck
with no result (compilation errors).
Thanks.
JavaScript
x
14
14
1
2
const pipeline = [
3
{
4
$match: {
5
[this.countryOriginFieldName!]: {
6
$in: members
7
},
8
**keyToCheck**: {
9
$nin: dictionaryNotAbsoluteFieldList
10
}
11
}
12
},
13
14
UPDATE: try with this example:
JavaScript
1
31
31
1
var keyToCheck = "indicator";
2
var queryMatch = {"`$${keyToCheck}`": "US$millions"}
3
printjson(queryMatch);
4
5
db.getCollection("temp_collection").aggregate([
6
{
7
$match: queryMatch
8
},
9
{$project: {indicator: 1, value: 1}}
10
]
11
);
12
13
14
15
db.getCollection("temp_collection").insertMany([
16
{
17
"indicator" : "US$millions",
18
"value" : 1.0
19
},
20
{
21
"indicator" : "US$millions",
22
"value" : 2.0
23
},
24
{
25
26
"indicator" : "EUROmillions",
27
"value" : 3
28
}
29
]);
30
31
Desired output:
JavaScript
1
9
1
{
2
"indicator" : "US$millions",
3
"value" : 1.0
4
}
5
{
6
"indicator" : "US$millions",
7
"value" : 2.0
8
}
9
Advertisement
Answer
Query
- the [keyToCheck] is to take the value of the variable, its not an array
- here its assumed that you want to project also the keyToCheck, and not always project the indicator
JavaScript
1
11
11
1
var keyToCheck = "indicator";
2
3
db.getCollection("temp_collection").aggregate([
4
{
5
$match: {[keyToCheck]: "US$millions"}
6
},
7
{$project: {[keyToCheck]: 1, value: 1}}
8
]
9
);
10
11
This will work, key will be just a string,and in project also just a string.
You dont need $
or $$
with this query.