DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Mongo DB: Update data using `.forEach()`

db.getCollection("posts")
  .find({})
  .forEach((item) => {
    const newValues = item.resources
      ? item.resources.map((label) => ({ label }))
      : [];
    item.resources = newValues;

    db.posts.save(item);
  });
Enter fullscreen mode Exit fullscreen mode

Task: Convert an array of string into array of object.
.forEach() can be used for some complex operations/migrations


Before: { _id: jf340f34f..., resources: [‘R1’] }

After: { _id: jf340f34f..., resources: [{label: ‘R1’}] }

Top comments (0)