Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB extract value from array of objects into simple array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading