// 為每一個文章文檔新增一個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}, })