Method: BSON::Document#slice

Defined in:
lib/bson/document.rb

#slice(*keys) ⇒ BSON::Document

Slices a document to include only the given keys. Will normalize symbol keys into strings. (this method is backported from ActiveSupport::Hash)

Examples:

Get a document/hash with only the name and age fields present

document # => { _id: <ObjectId>, :name => "John", :age => 30, :location => "Earth" }
document.slice(:name, 'age') # => { "name": "John", "age" => 30 }
document.slice('name') # => { "name" => "John" }
document.slice(:foo) # => {}

Parameters:

  • *keys (Array<String, Symbol>)

    Keys, that will be kept in the resulting document

Returns:

Since:

  • 4.3.1



289
290
291
292
293
294
295
# File 'lib/bson/document.rb', line 289

def slice(*keys)
  keys.each_with_object(self.class.new) do |key, hash|
    if key?(key)
      hash[key] = self[key]
    end
  end
end