MongoDB Change The Type of a field in a Nested Array

Today in this article, we will learn MongoDB Change The Type of a field in a Nested Array.

In our previous article, we already learn how to use Mongo Compass UI to change the type of a field.

We also looked at basic aggregation Expression Operators –

If you are interested to know above discussed approaches, please visit the below article,

We will cover below aspects in this article,

I have a below Mongo schema where Array element Books contains the price field which is of type Int.

We will change its datatype from Int to String type using the below techniques discussed.

below have sample schema where the price field type is Int currently. I would like to change its type from int to String type.

Sample schema

If using MongoDB 4.2 and above version – Change the data type

If you are using MongoDB 4.2 and above version then using updateMany function file name change can be achieved as below,

Change data type using updateMany and $set

db.Books.updateMany(
{},
[
  { 
      $set: { 
          Books: { 
              $map: { input: "$Books", in: { $mergeObjects: [ "$$this", { price: { $toString: "$$this.price" } } ] } }
          }
      }
  }
] 
)

If using MongoDB 4.0 and below version – Change the data type

If you are using MongoDB 4.0 and below version then using aggregation pipeline field name change can be achieved as below,

Change data type using aggregation pipeline,

db.Books.aggregate([ 
  { 
      $addFields: { 
          Books: { 
              $map: { input: "$Books", in: { $mergeObjects: [ "$$this", { price: { $toInt: "$$this.price" } } ] } }
          }
      }
  }
] ).forEach( doc => db.Books.updateOne( { _id: doc._id }, { $set: { Books: doc.Books } } ) )

Once executed, the data type change from int to string will be completed.

Please see below the result where int type is changed to string type.

MongoDB Change The Type of a field in a Nested Array

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



One thought on “MongoDB Change The Type of a field in a Nested Array

Leave a Reply

Your email address will not be published. Required fields are marked *