How to use a variable value as a field in aggregation query ($group)?

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!

This question has more to do with JavaScript than MongoDB.

What you want is called computed property names.

2 Likes

Thanks! By that, it would be like this right?

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

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.

Maybe this helps you @marc : Update nested object by key - #5 by santimir

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.