Home > Enterprise >  MongoDB: append as field the matched element from array
MongoDB: append as field the matched element from array

Time:10-31

I have the following code:

const array = ['a', 'b', 'c']

await collection.aggregate([
  { 
    $match: { 
      codes: { $in: array } 
    }
  },
  { 
    $addFields: { matchedField: "codes.$" } // <--- does not work
  }, 
]).toArray();

I need to append the matched element from within array to the returned results. Is it possible to do that?

My collection contains documents with the following scheme:

{
  "color": "red",
  "codes": [ "b" ]
}

I need the aggregation directive to return this:

{
  "color": "red",
  "codes": [ "b" ],
  "matchedField": "b",
}

CodePudding user response:

$filter

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $filter: {
          input: "$codes",
          as: "c",
          cond: {
            $in: [
              "$$c",
              [
                "a",
                "b",
                "c"
              ]
            ]
          }
        }
      }
    }
  }
])

mongoplayground


$setIntersection

db.collection.aggregate([
  {
    "$match": {
      "codes": {
        "$in": [
          "a",
          "b",
          "c"
        ]
      }
    }
  },
  {
    "$set": {
      codes: {
        $setIntersection: [
          "$codes",
          [
            "a",
            "b",
            "c"
          ]
        ]
      }
    }
  }
])

mongoplayground

  • Related