Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to delete a field in a document using ROR.

I have already tried

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

But they both set the attribute to nil and it is still present in the object.

I want it to vanish from my document. Any help is welcome.

like image 621
Deepika Kamboj Avatar asked May 08 '15 09:05

Deepika Kamboj


People also ask

How do I remove a field from a document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.


1 Answers

When you access a document via mongoid, it returns you a Ruby object. You can actually see the data stored in the document only via mongo shell (just type 'mongo' in you terminal).

The object is created by Mongoid (MongoDB ODM/wrapper for rails). This object may occasionally look different from the document.

For example

When you unset a field, that field is entirely removed from that document. BUT, since your model still has that field on it, MONGOID returns you a nil attribute for that field, instead of giving you different number of fields for 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, we 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 however you still dont want to see the field in your rails console (mind you, this is not taking up any extra space in db) you can always remove the field from the model. If you do that, you will no longer be able to access this field through rails/mongoid on any object. It will only be present on the document and accessible through mongo shell.

like image 125
Shifa Khan Avatar answered Oct 24 '22 16:10

Shifa Khan