1

I have a collection of documents that I initially set up like this:

{
  _id: "some_id",
  data: [
    {
      _id: "_id_foo",
      value: "foo"
    },
    {
      _id: "_id_bar",
      value: "bar"
    }
  ]
}

Now, I realized I don't need the value field, so I can turn the array of objects into an array of strings ["_id_foo", "_id_bar"]. I'm trying to build a pipeline to accomplish this, but I'm failing miserably.

If it's easier, I can also create a data_new array and delete the old one later.

Thanks!

1
  • 1
    Just use $map for this Commented Oct 20, 2022 at 9:03

1 Answer 1

2

You can use the map operator and convert the array of objects to array of strings.

db.collection.aggregate([
  {
    $addFields: {
      data: {
        $map: {
          input: "$data",
          as: "data",
          in: "$$data._id"
        }
      }
    }
  }
])

Playground

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

2 Comments

Thanks, that did the trick! I didn't know about map
If the goal is to persist this change permanently, then consider using this aggregation pipeline as the second argument to the update command

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.