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
- Get All collections in a database.
- Loop on that collections and find data in 'version' field with type NumberInt (In MongoDB it calls: $type = 16).
- 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.
That's just the basics. If you need more deep learning about MongoDB, you can take the following cheap course:
- MongoDB - The Complete Developer's Guide 2025
- The Complete MongoDB Course
- Node.js, Express, MongoDB & More: The Complete Bootcamp
- MongoDB - The Ultimate Administration and Developer's Guide
- MongoDB Masterclass: Excel in NoSQL & Pass Certification!
- MongoDB Associate Developer Exam - Practice Tests
- MongoDB Associate Database Administrator DBA Exam - Tests
- MongoDB - Learn NoSQL Databases - Complete Bootcamp
Thanks.