Nerver Corameiro
Nerver Corameiro

Reputation: 160

Move field to a specific object in an array in MongoDB

Here's my data:

{
  foos: [
    { _id: 1 },
    { _id: 2 },
    { _id: 3 }
  ],
  bar: "baz"
}

Now I wanna move field bar into foos object with _id = 2 to have this:

{
  foos: [
    { _id: 1 },
    { _id: 2, bar: "baz" },
    { _id: 3 },
  ]
}

How can I do this using aggregation framework?

Upvotes: 1

Views: 101

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $map to iterate loop of foos and check _id: 2 condition, if match then return bar object and merge with current object $mergeObjects
db.collection.aggregate([
  {
    $project: {
      foos: {
        $map: {
          input: "$foos",
          in: {
            $cond: [
              { $eq: ["$$this._id", 2] },
              { $mergeObjects: ["$$this", { bar: "$bar" }] },
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Playground

Upvotes: 2

Related Questions