我的MongoDB数据库非常大(大约1000万个项目使用1000 MB的磁盘空间(,但它的文档没有基于标题的slug。目前,一个文档如下所示:
{
"_id": {
"$oid": "630f3c32c1a580642a9ff4a0"
},
"title": "This is a title",
"Post": "this is a post"
}
但我想要这个
{
"_id": {
"$oid": "630f3c32c1a580642a9ff4a0"
},
"title": "This is a title",
"slug": "this-is-a-title",
"Post": "this is a post"
}
您可以在更新管道中使用$replaceAll
和$toLower
:
db.collection.update(
{},
[{$set: {
slug: {
$replaceAll: {
input: {$toLower: "$title"},
find: " ",
replacement: "-"
}
}
}}],
{multi: true}
)
看看它是如何在操场上工作的例子
当我在mongodb 5.1.0上尝试接受的答案时,我得到了TypeError: <collection-name>.update is not a function
,所以我使用下面的代码来完成。
const products = db.collection("Products");
await products.updateMany({},
[
{
$set: {
slug: {
"$replaceAll": {
input: {
$toLower: "$name"
},
find: " ",
replacement: "-"
}
}
}
}
])
将$name
替换为要创建段塞的属性。此外,不要忘记用您的收藏名称替换收藏名称;D