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

Change in behavior with MongoDB projections and Mongoid 'only' method.

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

      According to the MongoDB documentation, the _id field is returned by default when using projections.

      Using version 3.1.5

      irb(main):010:0> m = Member.only('email').first
      
      MOPED: QUERY  database=xxx collection=members selector={"$query"=>{}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields={"email"=>1} (1.0500ms)
      
      irb(main):011:0> m.attributes
      => {"_id"=>"5140fcd180fcd02f93000001", "email"=>"x@x.com"}
      

      the id attribute is available

      irb(main):012:0> m.id
      => "5140fcd180fcd02f93000001"
      

      Using version 4.0.0beta1

      pry(main)> m = Member.only('email').first
      
      MOPED: QUERY database=xxx collection=members selector={"$query"=>{}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields={"email"=>1} runtime: 0.6460ms
      
      pry(main)> m.attributes
      => {"_id"=>BSON::ObjectId('51350cef9ebea4769b000001'), "email"=>"x@x.com"}
      
      pry(main)> m.id
      ActiveModel::MissingAttributeError: Missing attribute: '_id'.
      

      But now, you must explicitly include 'id' or '_id' in the only call

      pry(main)> m = Member.only('email', 'id').first
      pry(main)> m.attributes
      => {"_id"=>BSON::ObjectId('51350cef9ebea4769b000001'), "email"=>"x@x.com"}
      
      pry(main)> m.id
      => BSON::ObjectId('51350cef9ebea4769b000001')
      

      The 3.1.5 behavior seems more consistent with what MongoDB is doing in that the id attribute is available by default instead of having to explicitly include 'id' in all calls to only.

            Assignee:
            Unassigned Unassigned
            Reporter:
            davebell davebell
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: