Home > front end >  MongoDB extract value from array of objects into simple array
MongoDB extract value from array of objects into simple array

Time:10-20

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!

CodePudding user response:

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

  • Related