zoukankan      html  css  js  c++  java
  • 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},
    })
  • 相关阅读:
    【筛法求素数】Codeforces Round #426 (Div. 1) A. The Meaningless Game
    【构造】AtCoder Regular Contest 079 F
    【贪心】AtCoder Regular Contest 079 E
    【构造】AtCoder Regular Contest 079 D
    【树形dp】hdu6035 Colorful Tree
    【计算几何】【bitset】Gym
    【枚举】【高斯消元】Gym
    【矩阵乘法】Gym
    【枚举约数】Gym
    【置换群】【枚举约数】hdu6038 Function
  • 原文地址:https://www.cnblogs.com/funsion/p/4003483.html
Copyright © 2011-2022 走看看