Search code examples
javascriptmongodbmongooseaggregate

Mongo Project by referencing external Dictionary


I have a collection in MongoDB:

[
  {
    "uid": "a1"
  },
  {
    "uid": "a2"
  }
]

and a dictionary in my JS code

let dict = { "a1": "ref1", "a1": "ref2" };

I want to do an aggregate that will somehow join the two.

let k = ;

this.model.aggregate([
  {
    $match: {
      uid: { $in: Object.keys(dict) }
    }
  },
  {
    $project: {
      ref: // here is where I want to add the equivalent reference
    }
  }
])

The expected output would be something like this:

[{uid: "a1", ref: "ref1"}, {uid: "a2", ref: "ref2}]

Is there a way to get the reference from the dict into the $project?


Solution

  • I don't know if there is an easier way to do it, but here's how I achieved it:

    db.collection.aggregate([
      {
        $match: {
          uid: {
            $in: [
              "a1",
              "a2"
            ]
          }
        }
      },
      {
        "$project": {
          "array": {
            "$objectToArray": {
              "a1": "ref1",
              "a2": "ref2"
            }
          },
          "uid": 1,
          
        }
      },
      {
        "$project": {
          "ref": {
            "$filter": {
              "input": "$array",
              "as": "elem",
              "cond": {
                "$eq": [
                  "$$elem.k",
                  "$uid"
                ]
              }
            }
          },
          uid: 1,
        },
      },
      {
        "$project": {
          ref: {
            "$arrayElemAt": [
              "$ref.v",
              0
            ]
          },
          uid: 1,
        }
      }
    ])
    

    See it working here. I hope you get the idea and convert it into the nodejs equivalent version.