標籤:style blog color io ar for 資料 sp div
// 為每一個文章文檔新增一個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},})
mongoDB中批量修改欄位