我需要用随机值更新mongodb中文档的所有字段:
Site.updateMany({siteID: undefined || null}, {$set: {siteID: shortid.generate()}});shortid.generate()创建一个随机字符串。我的代码的问题是,所有字段都是用相同的随机字符串设置的,这使我认为函数只执行一次,然后更新到所有字段。
如何实现使用随机字符串更新所有文件?
发布于 2020-01-11 07:30:58
你有几个选择:
_id**'s v4.2或更高版本上的&如果您可以存储MongoDB的字符串值(它是唯一的),请尝试如下:**
在最新版本中,.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' } } }
])On MongoDB在v4.2:下面
您需要先获取,然后更新:
( 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)中获得_id的投影&在Step b)中,在从Step 1)迭代数组时使用::generate-random-string-characters-in-javascript创建随机字符串。
发布于 2020-01-11 00:52:28
您说得对,函数首先进行计算,其结果只传递给查询一次。
您需要分别更新每个文档。或者,您可以根据需要使用mapReduce转换每个文档,并将修改后的文档输出到另一个集合。
https://stackoverflow.com/questions/59690531
复制相似问题