Last Updated: February 25, 2016
·
7.15K
· maciejsmolinski

Mongoid: Remove unnecessary properties from documents

Assuming we've got such a model:

# -*- encoding : utf-8 -*-
class Topic
  include Mongoid::Document

  field :name, type: String

  # No Longer Supported Property:
  # field :type, type: Integer

end

And we'd like to clear all documents from no longer supported property (:type), in Mongoid it's as simple as running:

Topic.each { |topic| topic.unset(:type) }

2 Responses
Add your response

Nice one... really useful database optimisation.

over 1 year ago ·

Might be more efficient if you:

Topic.collection.update({},
                        { '$unset' => { type: 1 } },
                        multi: true)
over 1 year ago ·