Home > Enterprise >  Removing Dynamic Fields by Association in MongoDB Aggregation
Removing Dynamic Fields by Association in MongoDB Aggregation

Time:11-17

I'm trying to display a MongoDB aggregation result via react chartjs. in aggregation, I can remove one field whose value is static via the set operator. is there a way to remove a second field by an association whose value is dynamic? in the example below, {"A": "N"} denotes the field that is readily removed by the set operator, whereas {"A_count":1} denotes the corresponding dynamic field that I am trying to remove.

starting aggregation output

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"},{"A":"N"}],
  "A_count_set":[{"A_count":0},{"A_count":1}]
}]

set operation for static field removal

{$set: {
  A_set: {
    $filter: {
      input: "$A_set",
      as: "x",
      cond: { "$ne": [ "$$x", {"A":"N"}] }
    }
  }
}}

current aggregation output

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"}],
  "A_count_set":[{"A_count":0},{"A_count":1}]
}]

target aggregation output

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"}],
  "A_count_set":[{"A_count":0}]
}]

CodePudding user response:

  • $project merge two array with the same position
  • $set filter array
  • $addFields recover the original array
  • $project remove the merge array

aggregate

db.collection.aggregate([
  {
    $project: {
      anotherValue: {
        $map: {
          input: {
            $range: [
              0,
              {
                $size: "$A_set"
              }
            ]
          },
          as: "idx",
          in: {
            $mergeObjects: [
              {
                $arrayElemAt: [
                  "$A_set",
                  "$$idx"
                ]
              },
              {
                $arrayElemAt: [
                  "$A_count_set",
                  "$$idx"
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      anotherValue: {
        $filter: {
          input: "$anotherValue",
          as: "x",
          cond: {
            "$ne": [
              "$$x.A",
              "N"
            ]
          }
        }
      }
    }
  },
  {
    $addFields: {
      "A_set": {
        $map: {
          input: "$anotherValue",
          as: "a",
          in: {
            "A": "$$a.A"
          }
        }
      },
      "A_count_set": {
        $map: {
          input: "$anotherValue",
          as: "a",
          in: {
            "A_count": "$$a.A_count"
          }
        }
      }
    }
  },
  {
    "$project": {
      "anotherValue": 0
    }
  }
])

mongoplayground

  • Related