mongodb 如何在聚合中将null转换为string?

flvlnr44  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(159)

我的收藏看起来像这样:

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

但是我想把所有null的标题转换成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"
}
]

如何将所有具有空标题的文档的空标题转换为字符串?

b1zrtrql

b1zrtrql1#

您可以使用简单的更新:

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

了解它在playground example上的工作原理

ki0zmccv

ki0zmccv2#

三件事:

  • 筛选要更新{title:null}的项目
  • $set用于更改字段值的更新
  • 确保您可以更新多个文档

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

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

相关问题