MongoDB: How to Update All Collections in a Database

by Didin J. on Feb 18, 2017 MongoDB: How to Update All Collections in a Database

Sometimes we need to update data to all collections of same field with single query in MongoDB

This tutorial based on needed of update data in all collections of the same field in a database with the only single query. Let's started with a problem first.


Problem

We have to make a change of data type in application server which impacts on existing data in MongoDB database, this occurs error when calling data in an application server. It's telling the application that one field has different data type each of them. What we need is make all data on that fields have the same type.
For example:

  • All collection have same fields with the name 'version' which that field has a data type NumberInt.
  • The application change data type to NumberLong.
  • Error occurs in the application because existing data have the version with type NumberInt.

Solution

  1. Get All collections in a database.
  2. Loop on that collections and find data in 'version' field with type NumberInt (In MongoDB it calls: $type = 16).
  3. Loop on collections with version data type is NumberInt then replace with datatype NumberLong.

Command/Syntax

db.getCollectionNames().forEach(function (c) { db.getCollection(c).find({version: {$type: 16}}).forEach(function (x) {x.version=new NumberLong(x.version);db.getCollection(c).save(x)}) });

Simply as that.

Thanks.