skip to Main Content

I’m completely new to MongoDB. I’m using the free tier of cloud mongodb service where I’ve imported some data. How would I go about modifying some data. All documents in the collection called ‘transactions’ have fields called: "Transaction Name" and "Transaction Type", "Account Number". I’d like to change them to TransactionName and TransactionType, etc. Additionally, the Account Number has value of type number. I’d like to change it to string (and convert the value from number to string). All documents in the collection have this value (ie. no nulls) and all of them are of type number.

I can connect to mongosh or use a node script.
Thank you

2

Answers


  1. Simply use $rename. Should be something like this based on the mongo example:

    db.transactions.updateMany(
    {
      "$rename": {
        "Transaction Name": "TransactionName",
        "Transaction Type": "TransactionType",
        "Account Number": "AccountNumber"
      }
    })
    

    Example here.

    Login or Signup to reply.
  2. You can use update with aggregation pipeline

    db.collection.update({},
    [
      {
        "$set": {
          "TransactionName": "$Transaction Name",
          "TransactionType": "$Transaction Type",
          "AccountNumber": {
            $toString: "$Account Number"
          }
        }
      },
      {
        "$unset": [
          "Transaction Name",
          "Transaction Type",
          "Account Number"
        ]
      }
    ],
    {
      multi: true
    })
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search