how to use getLastError in pymongo?

2.5k views Asked by At

1,How can i get the return value of my operations in monogd, by python ?i know getLastError can be used in javascript.

2,is there limit to set modifer? if i use
collection.update({"notification":"yes"},{"$set":{ "idx":idx,"src_md5":src_md5,"src_size":src_size,"src_time":int(src_time)},"$addToSet":
{"server_list":host_name}})

it didn't work.
but when i use
collection.update({"notification":"yes"},{"$set":
{"idx":idx,"src_md5":src_md5,"src_size":src_size},"$set":
{"src_time":int(src_time)},"$addToSet":{"server_list":host_name}})
it worked.
why?

2

There are 2 answers

0
Ross On

1) You can use write concern keyword arguments, to ensure that getLastError is called. The various methods are described below:

  • safe: Use getlasterror for each write operation?
  • j or journal: Block until write operations have been commited to the journal. Ignored if the server is running without journaling. Implies safe=True.
  • w: (integer or string) If this is a replica set write operations won’t return until they have been replicated to the specified number or tagged set of servers. Implies safe=True.

You can set these write concerns at different levels depending on your needs:


2) Your query looks fine heres a test:


db.test2.save({notification: 'yes'})
db.test2.update({"notification": "yes"}, {
    "$set": {"idx": 'a', "src_md5": 'b', "src_size": 'c', "src_time": 1}, 
    "$addToSet": {"server_list": 'stackoverflow'}
})
db.test2.find()


{
    "_id" : ObjectId("4fc5decf0631996582479878"),
    "idx" : "a",
    "notification" : "yes",
    "server_list" : [
        "stackoverflow"
    ],
    "src_md5" : "b",
    "src_size" : "c",
    "src_time" : 1
}

0
Chintak Chhapia On

This worked for me

last_error = db.runCommand({"getLastError":1})