DEV Community

loading...

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

Mehul Lakhanpal
Full stack Developer | Micro-blogging on Web Development at codedrops.tech | Creator of File Ops, Note Box, GitHub Marker
Originally published at codedrops.tech ・1 min read
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’}] }

Discussion (0)