mongodb using dict variable as a bind for an aggregation pipeline

Viewed 31

This is my case: I have this variable named dummy, which contains an JS object. So, it looks like this:

var dummy_obj = {'a': 'qwerty1', 'b': 'poiuy2p', 'c': 'asdfg3'};

Then, I need to use the value dummy_obj['a'] as a bind variable in an aggregation pipeline. Suppose I have a collection named 'whatever' with a field named 'd', which contains the keys of the dummy object (or dictionary, as anyone wants to name it), among other fields like dOy (dayOfYear), some_key (containing some value), etc. I mean:

var dummy_obj = { 'a': 'qwerty1', 'b': 'poiuy2p', 'c': 'asdfg3' };
db.getCollection('whatever').aggregate([
    {
        $match: { dOy: 300 },
    },
    {
        $project: { _id: 0, some_key: 1, d: 1 },
    },
    {
        $addFields: { dummy: dummy_obj['$d'] },
    },
    {
        $project: { _id: 0, some_key: 1, d: 1, dummy: 1 },
    },
]);

The output cannot find the value from dummy_obj, which is undefined. But if I write dummy_obj instead of dummy_obj['$d'], the whole obj will be included in the output. Something similar happens if I write dummy: '$d', returning the same values as the field named 'd' (of course, I basically put the same values on a different key).

So, why does it not work? Is it a matter of syntax? Probable I'm getting the whole aggregation framework wrong. Where is the issue here?

Thanks in advance for your time and concerns.

Best regards.

PS: I'm using MongoDB 5.0.4, with mongosh as a shell command

1 Answers

You'll have to convert the input dummy_obj to an array, filter it based on $d value and then convert it back, like so:

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        "$mergeObjects": [
          "$$ROOT",
          {
            "$arrayToObject": {
              $map: {
                input: {
                  $filter: {
                    input: {
                      "$objectToArray": dummy_obj
                    },
                    cond: {
                      $eq: [
                        "$$this.k",
                        "$d"
                      ]
                    }
                  }
                },
                in: {
                  k: "dummy",
                  v: "$$this.v"
                }
              }
            }
          }
        ]
      }
    }
  }
])

Mongo Playground

Related