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 375A(同余)
    POJ 2377 Bad Cowtractors (最小生成树)
    POJ 1258 AgriNet (最小生成树)
    HDU 1016 Prime Ring Problem(全排列)
    HDU 4460 Friend Chains(bfs)
    POJ 2236 Wireless Network(并查集)
    POJ 2100 Graveyard Design(尺取)
    POJ 2110 Mountain Walking(二分/bfs)
    CodeForces 1059B Forgery(模拟)
  • 原文地址:https://www.cnblogs.com/funsion/p/4003483.html
Copyright © 2011-2022 走看看