1
0 Comments

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);
  });

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’}] }

Trending on Indie Hackers
38% of remote employees work from bed. What about you? 15 comments Notion or Airtable for database and research based products? 10 comments Twitter accounts directory 5 comments Launching a new feature: Video Reviews 3 comments I started The Peak (Morning Brew for Canada) and sold $150,000 worth of ads in year 1. Here's how. 3 comments Finding users that don’t follow a specific demographic? 2 comments