记录几个常用mongodb命令

in 默认分类 with 0 comment

去重

db.record.aggregate([{
    $group: {
        _id: {
            field: '$field'
        },
        count: {
            $sum: 1
        },
        dups: {
            $addToSet: '$_id'
        }
    }
},
{
    $match: {
        count: {
            $gt: 1
        }
    }
}]).forEach(function(it) {
    it.dups.shift();
    db.record.remove({
        _id: {
            $in: it.dups
        }
    });
});

forEach修改

db.record.find({
    type: 1,
    field: {
        '$exists': false
    }
}).forEach(function(it) {
    var s = 0;
    it.list.forEach(function(item) {
        s += NumberInt(item.score);
    });
    it.field= s / 5;
    db.record.save(it);

});

建立索引

db.record.createIndex({
    field: 1
},
{unique: true})
Responses