2

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 2

2

You can use a simple update:

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

See how it works on the playground example

Sign up to request clarification or add additional context in comments.

3 Comments

You'll need to set {multi:true} for all docs.
Only if you use update instead of updateMany
Good point! But your playground example won't use updateMany. I'm enjoying this speed game!
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
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.