How to convert null to string in aggregation?

How to convert null to string in aggregation?

Problem Description:

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?

Solution – 1

You can use a simple update:

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

See how it works on the playground example

Solution – 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
})
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject