skip to Main Content

My collection Looks like this:

[
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": "This is title one"
},
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": null
},
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": "This is title three"
}
]

But I want to convert every title that have null to string (not-found):

[
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": "This is title one"
},
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": "not-found" // null to be converted to string
},
{
  "_id": {
    "$oid": "638ecf5247cf747bdd862bfb"
  },
  "title": "This is title three"
}
]

How to convert null title to string for all documents that have null title?

2

Answers


  1. You can use a simple update:

    db.collection.updateMany({
      "title": null
    },
    {
      $set: {
        title: "not-found"
      }
    })
    

    See how it works on the playground example

    Login or Signup to reply.
  2. 3 things:

    • Filter the items that you want to update {title:null}
    • $set the update to change the field value
    • Ensure that you can update multiple documents

    Playground – https://mongoplayground.net/p/DfAWE1Swszb

    db.collection.update({
      title: null
    },
    {
      $set: {
        title: "not-found"
      }
    },
    {
      multi: true
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search