Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2559

Can't $inc and element of an array

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.0.14
    • Affects Version/s: None
    • Component/s: None
    • None

      It doesn't seem possible to

      $inc

      an element of an array.

      class IncTest
        include Mongoid::Document
      
        field :arr, type: Array, default: [0, 0]
        field :counter, type: Integer, default: 1
      end
      
      >> a = IncTest.new
      => #<IncTest _id: 50a76f83abddc1dfdc000001, _type: nil, arr: [0, 0], counter: 1>
      
      # an upsert with $inc of counter ... WORKS
      >> a.upsert({ '$inc' => { counter: 1 } })
        MOPED: 127.0.0.1:27017 UPDATE       database=inc_test collection=inc_tests selector={"_id"=>"50a76f83abddc1dfdc000001"} update={"$inc"=>{:counter=>1}, "$set"=>{"arr"=>[0, 0]}} flags=[:upsert] (0.1619ms)
      => true
      
      # an upsert with $inc of an array element ... FAILS
      >> a.upsert({ '$inc' => { 'arr.0' => 1 } })
        MOPED: 127.0.0.1:27017 UPDATE       database=inc_test collection=inc_tests selector={"_id"=>"50a76f83abddc1dfdc000001"} update={"$inc"=>{"arr.0"=>1}, "$set"=>{"arr"=>[0, 0], "counter"=>1}} flags=[:upsert] (0.1581ms)
      => true
      

      As you can see from the MOPED log from the second example, a

      $set

      of

      Unable to find source-code formatter for language: arr```. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
       is being appended to the command which clobbers the 

      $inc

      .
      
      I had initially thought this was because the 

      arr

       has a default, but even without that the 

      $set

       still occurs.
      
      For completeness, I'm trying to implement something like this:
      
      

      javascript
      db.inc_tests.update(

      { _id: ObjectId('50a76f83abddc1dfdc000001') }

      , { $inc:

      { counter: 1, 'arr.0': 1, 'arr.1': 1 }

      }, true)
      `

            Assignee:
            Unassigned Unassigned
            Reporter:
            al Antonio Lagrotteria
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: