pymongo 中自增列设置

阅读更多
1、在mongodb中可以采用js函数方法设置

> db.createCollection("counters")
{ "ok" : 1 }
> db.counters.insert({_id:"userid",sequence_value:0})
WriteResult({ "nInserted" : 1 })
> db.counters.find()
{ "_id" : "userid", "sequence_value" : 0 }

> function getNextSequenceValue(sequenceName){
... var sequenceDocument = db.counters.findAndModify(
...     {
...         query:{_id:sequenceName},
...         update:{$inc:{sequence_value:1}},
...         new:true
...     });
... return sequenceDocument.sequence_value;
... }
> db.person.insert({"_id":getNextSequenceValue("userid"), "loginname":"test", "password":"test"})
WriteResult({ "nInserted" : 1 })
> db.person.find()
{ "_id" : 1, "loginname" : "test", "password" : "test" }


在python脚本中调用时候使用db.eval()
#首先定义js
        fuc = '''
function getNextSequenceValue(sequenceName){
    var sequenceDocument = db.counters.findAndModify(
     {
         query:{_id:sequenceName},
         update:{$inc:{sequence_value:1}},
         new:true
     });
     return sequenceDocument.sequence_value;
}
        '''
#然后insert插入时候使用db.eval()
db.person.insert({"_id":db.eval(fuc, "userid"),
                  "loginname":loginname,
                  "password":password})

你可能感兴趣的:(pymongo 中自增列设置)