0

I am trying to change int to string in mongodb for CardNumber.The script shows executed successfully but datatype does not change.Please let me know how to resolve this issue.

GiftCardSale
[0]CardNumber
   Amount
[1]CardNumber
   Amount
db.SalesOrder2.find({"GiftCardSale.$[i].CardNumber": {$exists:true}}).sort({_id:1}).skip(0).limit(100)
    .forEach( function(x) {
        db.SalesOrder2.update({_id: x._id}, {$set: {"GiftCardSale.$[i].CardNumber": 
        x.GiftCardSale.$[i].CardNumber.toString()}});
    }
);

1 Answer 1

1

To change multiple fields data types in mongodb:

In this case we are changing fields data type from int to string.

1.login mongo shell(mongosh) with the database address

2.type mongosh command: show dbs to look up your database

3.type mongosh command: use to select the database you want to update with

4.type in like below:

db.<dbname>.updateMany(
  { <field> : { $type: 16 } },
  [{ $set: { <field>: { $toString: "$<field>" } } }]
)

5.bingo!

PS: All the variables/fields in angle brackets, AKA within "" should be replaced with your actual variable/field name for example that would become:

db.mydatabase.updateMany(
  { myfield : { $type: 16 } },
  [{ $set: { myfield: { $toString: "$myfield" } } }]
)

For other cases, simply change the function from "toString" to other functions you want. Also if you want to match the input field type with other format such as string, you will need to change $type: 16 to $type: 1

For specific type number matching(with an awesome graph demonstration), checkout below https://data-flair.training/blogs/mongodb-data-types/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.