skip to Main Content

I have this collection:

{
     A:1
     B:2
      :3
     D:4
}

We need to replace a whitespace with C for example, how can I achieve this?

Like this

{
  A:1
  B:2
  C:3
  D:4
}

I tried renaming, but it’s not possible and the only thing I can think of is rebuilding a collection.

2

Answers


  1. If the whitespace is a space character s then you can simply look for that and use $rename to rename that key:

    db.collection.updateOne({' ':3}, { $rename: { ' ': 'C' } });
    

    If you have multiple instances of the whitespace key you can update them all with:

    db.collection.updateMany({}, { $rename: { ' ': 'C' } });
    
    Login or Signup to reply.
  2. We can use $rename operator for this.

    db.collection.update({"_id": 0},{  "$rename": {    " ": "C"  }})
    

    Ref: https://mongoplayground.net/p/mmS2icBgOTO

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