marc
(Marc)
December 17, 2022, 1:47am
#1
Hi all, I would like to define modifierName
from email
variable and use it as a field in an aggregation query (specifically $group). How can I achieve that with this code?
let data = await Request.aggregate([
{ $match: searchFilters },
{ $lookup: {
from: 'user',
localField: 'user',
foreignField: '_id',
as: 'modifier',
} },
]);
let email = data.email; // julio@email.com
let modifierName = email.split('@')[0]; // julio
data = await Request.aggregate([
{ $match: searchFilters },
{ $lookup: {
from: 'user',
localField: 'user',
foreignField: '_id',
as: 'modifier',
} },
{ $group: {
_id: {
date: groupIdDate,
},
modifierName: { $sum: 1 }
} }
]);
Here is this question in a picture :
Any suggestion is appreciated, thank you!
steevej
(Steeve Juneau)
December 17, 2022, 1:57pm
#2
This question has more to do with JavaScript than MongoDB.
What you want is called computed property names .
2 Likes
marc
(Marc)
December 18, 2022, 4:00am
#3
Thanks! By that, it would be like this right?
steevej
(Steeve Juneau)
December 18, 2022, 1:53pm
#4
The best way to find out is to try it.
Using mongosh
mongosh > modifierName = "foo"
< 'foo'
mongosh > bar = { [modifierName] : "bar" }
< { foo: 'bar' }
mongosh > bar
< { foo: 'bar' }
1 Like
marc
(Marc)
December 19, 2022, 8:38am
#5
Thanks!
But what if I would like to use result of previous stage in MongoDB?
Let’s say, I have modifier
values as a result of $unwind stage which I would like to use it as a field in the next stage ($group), like in the picture below :
I tried to define it as $$modifier
, but it failed :
...
{
'$group': {
'_id': {
'date': {
'$dateToString': {
'format': '%d/%m/%Y',
'date': '$updatedTime'
}
}
},
'$$modifier': { '$sum': 1 }
}
},
...
Is it possible to label a field using result in the previous stage?
Edit :
Changing '$$modifier': { '$sum': 1 }
to :
...
[modifier]: { '$sum': 1 }
// OR
['$modifier']: { '$sum': 1 }
...
said : Stage must be a properly formatted document.
cris
(Cris)
December 19, 2022, 2:40pm
#6
2 Likes
system
(system)
Closed
December 24, 2022, 2:40pm
#7
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.