首页 > 解决方案 > 使用随机值更新 mongodb 中的许多字段

问题描述

我需要使用随机值更新 mongodb 中文档的所有字段:

Site.updateMany({siteID: undefined || null}, {$set: {siteID: shortid.generate()}});

shortid.generate()创建一个随机字符串。我的代码的问题是所有字段都设置了相同的随机字符串,这让我认为该函数执行一次,然后更新到所有字段。
如何使用随机字符串更新所有文件?

标签: mongodbmongoose

解决方案


你有几个选择:

在 MongoDB v4.2 或更高版本上 && 如果你可以存储 MongoDB 的_id字符串值(这是唯一的)试试这个 ::

由于.updateMany()在最新版本中接受聚合管道:

Site.updateMany(
    // Filtering documents to check siteID not exists & equals to null (just null check will make sure field doesn't exists as well)
    { siteID: null },
    [
        { $set: { siteID: { $toString: '$_id' } } }
    ])

在 v4.2 以下的 MongoDB 上:

您需要先获取然后更新:

a) 获取文件:

let response = Site.aggregate([{$match : {date : null}}, {$project :{siteID : {$toString : '$_id'}}}])

b) 更新文件:

let bulkArr = [];
response.forEach(element => {
    bulkArr.push({
        updateOne: {
            "filter": { _id: element._id }, // Use mongoose.Types.ObjectId(element._id) if needed.
            "update": { '$set': { 'siteID': element.siteID } }
        }
    })
});

let updateResult = await Site.bulkWrite(bulkArr)
console.log('matchedCount ::', updateResult.matchedCount, 'modifiedCount ::', updateResult.modifiedCount)

以防万一,如果您不想存储 的字符串值那么_id在从.Step a)_idStep b)Step 1)


推荐阅读