0

I'm trying to write an aggregation in MongoDB which would result as shown below. Please suggest to me how to build MongoDB Aggregation in order to achieve my output.

Collection (input): I would like to add a key test_id to the obj.test_id object based on matching condition test_id.

Please suggest an optimal way of writing a MongoDB query to achieve my result.

1 Answer 1

1
  1. $set - Set dataObj.cFS.data field.

    1.1. $map - Iterate each element in dataObj.cFS.data and return a new array.

    1.1.1. $mergeObjects - Merge the current iterate object (data) with the result from 1.1.1.1.

    1.1.1.1. $first - Get the first filtered document from the result 1.1.1.1.1.

    1.1.1.1.1. $filter - Filter the document(s) from the cfCoreData array by matching the cf_id.

db.collection.aggregate([
  {
    $set: {
      "dataObj.cFS.data": {
        $map: {
          input: "$dataObj.cFS.data",
          as: "data",
          in: {
            $mergeObjects: [
              "$$data",
              {
                $first: {
                  $filter: {
                    input: "$cfCoreData",
                    cond: {
                      $eq: [
                        "$$data.cf_id",
                        "$$this.cf_id"
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the detailed answer! This helps in my usecase! Appreciate your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.