mongodb - 使用随机值更新 mongodb 中的许多字段
问题描述
我需要使用随机值更新 mongodb 中文档的所有字段:
Site.updateMany({siteID: undefined || null}, {$set: {siteID: shortid.generate()}});
shortid.generate()
创建一个随机字符串。我的代码的问题是所有字段都设置了相同的随机字符串,这让我认为该函数执行一次,然后更新到所有字段。
如何使用随机字符串更新所有文件?
解决方案
你有几个选择:
在 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)
_id
Step b)
Step 1)
推荐阅读
- spring-boot - 在 spring-boot 中使用 kotlin 挂起函数创建名称为“requestMappingHandlerMapping”的 bean 时出错
- python - 更改 matplotlib 中绘图和轴的颜色
- node.js - 后端未收到来自 xhr 请求的数据
- laravel - 如何在同一控制器函数中创建模型后立即检索模型的 ID?
- reactjs - React.js:Onblur 事件触发每次按键
- python-3.x - 如何在一个屏幕上为 twinx 或 twiny 方法绘制 4 个图形?
- java - Java ArrayList - 8x8 游戏板
- neo4j - 如何在neo4j中使用like子句和正则表达式传递参数
- python - django orm 如何确保 postgres 数组字段不是空列表?
- powerbi - Power BI - 创建新度量时,如何下拉到新行?