mongoDB中批量修改字段
// 为每一个文章文档新增一个image_count字段,用于记录此文章包含的图片个数 db['test.articles'].find({'title':'wfc test'}).forEach( function(thisArticle){ // 这里要强制转为整形,否则会变成浮点数 // 要用NumberInt转换为整形,用parseInt得到依然是浮点数 imageCount = NumberInt( thisArticle['article_images'].length ) db['test.articles'].update({'_id':thisArticle['_id']}, {$set:{'image_count':imageCount}} ) }) // 比较精简干练的写法 db.test.articles.find({'title':'wfc test'}).forEach( function(thisArticle){ thisArticle.image_count = NumberInt( thisArticle.article_images.length ) db.test.articles.save(thisArticle) }) // 将文档的字段放入嵌套数组后,再删除该字段(数据结构修改) db['test.game'].find({'article_image':{$exists:0}}).forEach( function(thisArticle){ articleImage = {'remote':thisArticle.game_icon, 'local':thisArticle.game_local_icon, 'original':thisArticle.game_remote_icon, 'upload':thisArticle.icon_upload} thisArticle.image_upload = thisArticle.icon_upload thisArticle.modify_time = thisArticle.spider_time thisArticle.article_image = [] thisArticle.article_image.push(articleImage) delete thisArticle.game_icon delete thisArticle.game_local_icon delete thisArticle.game_remote_icon delete thisArticle.icon_upload db['test.game'].save(thisArticle) }) // 按名称分组统计 db['test.articles'].group({ key:{'name':1}, condition:{'name':{$exists:1}}, $reduce:function(curr, result) { result.total += 1 }, initial:{total:0}, })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?