mongodb技巧总结

来源:互联网 发布:matlab矩阵求转置 编辑:程序博客网 时间:2024/06/01 08:59

1) 条件操作符

$gt : >

$lt : <

$gte :  >=

$lte : <=

$ne : !=

$in : in

$nin : not in

$or : or


2) 正则操作符

$regex


3) 关联查询

$DBref, $id


4) pull & push

    应用 : 例如在消息的已读和未读的管理
    pull : 将数组里的某个值移除
    db.message.update({ "_id" : ObjectId(id) }, { "$pull" : { "readed" : DBRef("user", ObjectId(userid)) } })
    push : 增加数组一个值得

db.message.update({ "_id" : ObjectId(id) }, { "$push" : { "readed" : DBRef("user", ObjectId(userid)) } })


5) 判断字段是否存在

db.users.find({name: {$exists: true}})

    db.users.find({phone: {$exists: false}})


6) 更新和移除字段

db.user.update({}, {"$set" : {"isgroup" : 1}, {multi : true}})

db.recharge.update({}, { $unset : { "profit_process" : 1 } }, { multi : true })


7) 统计

    关键字 : aggregate
    里面是一个数组, 将从上而下地过滤数据, 并统计在"group"里面
    sale = db.order.aggregate([
        {
            "$match" : where
        },
        {
            "$group" : {    
                "_id" : "$user",
                "count" : { "$sum" : 1 },
                "amount" : { "$sum" : "$amount" },
                "profit" : { "$sum" : "$profit" }
            }
        }
        # 这里还可以加其他条件, 例如分页
    ])


8) 更改字段名称

关键字 : $rename

db.collection.update({}, {"$rename" : {"oldname" : "newname"}}, {"multi" : true})

0 0
原创粉丝点击