Delete a field in a document in mongodb - Rails + Mongoid -


i want delete field in document using ror.

i have tried

  1. book.remove_attribute(:name)
  2. book.unset(:name)

but both set attribute nil , still present in object.

i want vanish document. welcome.

when access document via mongoid, returns ruby object. can see data stored in document via mongo shell (just type 'mongo' in terminal).

the object created mongoid (mongodb odm/wrapper rails). object may different document.

for example

when unset field, field entirely removed document. but, since model still has field on it, mongoid returns nil attribute field, instead of giving different number of fields objects of same model.

model book.rb

class book   include mongoid::document    field :name   field :author end 

in rails console, type

 book.create(name: "b1", author: "a1")     => #<book _id: 555231746c617a1c99030000, name: "b1", author: "a1"> 

in mongo shell

db.books.find() { "_id" : objectid("555231746c617a1c99030000"), "name" : "b1", "author" : "a1" } 

now, unset.

in rails console

book.first.unset(:name)  => #<book _id: 555231746c617a1c99030000, name: nil, author: "a1"> 

in mongo shell

db.books.find() { "_id" : objectid("555231746c617a1c99030000"), "author" : "a1" } 

if still dont want see field in rails console (mind you, not taking space in db) can remove field model. if that, no longer able access field through rails/mongoid on object. present on document , accessible through mongo shell.


Comments