目前,文档如下所示:

{
  "_id": {
    "$oid": "630f3c32c1a580642a9ff4a0"
  },
  "title": "This is a title",
  "slug": "this-is-a-title",
  "Post": "this is a post"
}

但我希望是这样的:

{
  "_id": {
    "$oid": "630f3c32c1a580642a9ff4a0"
  },
  "title": "This is a title",
  "slug": "this-is-a-title-548631",
  "Post": "this is a post"
}

如何在所有文档中的Slug结尾处添加6位随机数?

推荐答案

您可以使用$rand生成随机数,与其他一些运算符组合可以强制6位数约束,如下所示:

db.collection.updateMany({},
[
  {
    $set: {
      slug: {
        $concat: [
          "$slug",
          "-",
          {
            $toString: {
              $round: {
                $add: [
                  {
                    $multiply: [
                      {
                        $rand: {}
                      },
                      899999
                    ]
                  },
                  100000
                ]
              }
            }
          }
        ]
      }
    }
  }
])

Mongo Playground

(这将给出000123000到999999的范围内的结果),如果您希望允许0个前缀,例如000123,则仍然可以使用相同的方法,并根据数字长度填充零.

Mongodb相关问答推荐

更新查询mongoose 中的礼宾更新字段

通过mongoDB中的查找从管道中删除被阻止的用户

MongoDB Aggregate-如何在条件中替换字符串中的变量

在MondoDB中:将对象数组从切片索引数组切片,并通过聚合推入数组

执行聚合以消除重复并获得唯一计数

MongoDB - 将对象转换为数组

MongoDb聚合查询问题

错误起草的 MongoDB 聚合管道 $match 阶段

在数据中只有月份和年份的 mongodb 中字符串的日期时间

Mongo C#忽略属性

MongoDB 更改流副本集限制

无法提取地理键,经度/纬度超出范围

Stripe:必须提供来源或客户

mongo php副本连接非常慢

Django admin 和 MongoDB,可能吗?

Python Django-REST-framework 和 Angularjs 的文件夹 struct

mongoose 使用 $cond 中的 $exists 聚合

获取 mongodb 中所有唯一标签的列表

如何在 golang 和 mongodb 中通过 id 查找

MongoDB:删除唯一约束