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}, })
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。