Home > Net >  Mongo aggregation $lookup
Mongo aggregation $lookup

Time:06-22

I have a collection of tags and a collection of objects that have an array of those tags. I'm trying to get a list of tags with a list of projects in which they are used.

tag:

{
...
 "tag":"test"
...
}

object:

{
...
 "tags": ["test", "test_1"]
...
}

Expected Result:

{
...
 "tag": "test",
 "objects": [
   {
    ...
    "tags": ["test", "test_1"]
    ...
   }
  ]
...
}

I am trying to execute the following lookup.

{
  from: 'object',
  let: {
    tag: "$tag"
  },
  pipeline: [
      { $match: {
          $expr: { 
            $eq: ["$tags", "$$tag"] 
          }
        } 
      }
  ],
  as: 'objects'
}

But he does not unite them. And if tags would not be an array, but a string, then the lookup above works fine, but I need it to be an array. If I replace $eq with $in it will complain that the expected second argument is a string, but it expects an array. Swapping arguments ($in: ["$$tag", "$tags"]) doesn't work either. I don't understand how to do it right.

CodePudding user response:

You can use $in

db.tag.aggregate([
  {
    "$lookup": {
      from: "object",
      let: {
        tag: "$tag"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$$tag",
                "$tags"
              ]
            }
          }
        }
      ],
      as: "objects"
    }
  }
])

Working Mongo playground

  • Related