4

I have two arrays:

[
  {
    name: 'First object',
    value: 1
  },
  {
    name: 'Second object',
    value: 2
  },
  {
    name: 'Third object',
    value: 3
  },
];

and

[
  {
    name: 'First object',
    anotherValue: 1,
  },
  {
    name: 'Second object',
    anotherValue: 2,
  },
  {
    name: 'Third object',
    anotherValue: 3,
  },
];

Could I get new array using these two using MongoDB aggregation? I mean:

[
  {
    name: 'First object',
    value: 1,
    anotherValue: 1,
  },
  {
    name: 'Second object',
    value: 2,
    anotherValue: 2,
  },
  {
    name: 'Third object',
    value: 3,
    anotherValue: 3,
  },
];

I've tried to use facet, concatArrays and group to get that array but it doesn't work:

{
  $facet: {
    $firstArray: [...],
    $secondArray: [...],
  }
  $project: {
    mergedArray: {
      $concatArrays: [firstArray, secondArray],
    }
  },
  $group: {
    _id: {
      name: '$mergedArray.name'
    },
    value: {
      $first: '$mergedArray.value'
    },
    anotherValue: {
      $first: '$mergedArray.anotherValue'
    }
  },
}

But $anotherValue is always null.

Is there a neat way of achieving this by the aggregation framework?

1 Answer 1

11

To match by name, run the query below:

db.collection.aggregate([
  {
    $project: {
      anotherValue: {
        $map: {
          input: "$firstArray",
          as: "one",
          in: {
            $mergeObjects: [
              "$$one",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$secondArray",
                      as: "two",
                      cond: { $eq: ["$$two.name", "$$one.name"]}
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }
])

MongoPlayground | Arrays with the same position + name value

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

Comments

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.