mongodb-haskell / mongodb

MongoDB driver for Haskell
http://hackage.haskell.org/package/mongoDB
Apache License 2.0
170 stars 44 forks source link

How to clamp while decrementing #133

Open TheOddler opened 2 years ago

TheOddler commented 2 years ago

I have a document where I want to decrement a field by 1, but it should never go negative. However, I can't figure out how to do this.

I tried two things (and a bunch of variations on this):

      findAndModifyOpts
        ( select ...)
        FamUpdate
          { famUpdate =
              [ "$inc" =: ["count" =: ((-1) :: Int)],
                "$max" =: ["count" =: (0 :: Int)]
              ],
            famNew = False,
            famUpsert = False
          }

and

      findAndModifyOpts
        ( select ...)
        FamUpdate
          { famUpdate =
              [ "$set" =: 
                  [ "count" =:
                    [ "$max" =:
                      [ "$max" =: [Int32 0, Int32 0],
                        "$subtract" =: [String "$count", Int32 1]
                      ]
                    ]
                  ]
              ],
            famNew = False,
            famUpsert = False
          }

But both end up giving a document not found error.

How do I properly do this?