Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

mongodb - How to toggle a boolean field in one document with atomic operation?

Is there any way to toggle the boolean field of ONE document in MongoDB with atomic operation? Say, (In python)

cl.update({"_id": ...}, {"$toggle": {"field": 1}})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Right now, I don't think it's possible to do this with one operation. The bitwise operators (http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit) don't have a '$xor' yet although I've a patch for it.

Right now the workaround I think think of is by always using '$inc':

cl.update( { "_id": ...}, { '$inc' : { 'field' : 1 } } );

Then instead of checking for true or false, you can do check whether an item is "true":

cl.find( { "_id": ..., 'field' : { '$mod' : [ 2, 1 ] } );

IE, you using the modulo operator to see whether it's even or uneven with even being "unset", and uneven being "set". If you want to have the oppposite behaviour (ie, find all items that don't have the flag set), then use

[ 2, 0 ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...