Home > Mobile >  How to convert null to string in aggregation?
How to convert null to string in aggregation?

Time:12-06

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?

CodePudding user response:

You can use a simple update:

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

See how it works on the playground example

CodePudding user response:

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
})
  • Related