如何使用MongoMapper重命名Mongodb集合中的列?

时间:2013-01-21 11:11:10

标签: mongodb mongomapper

Mongodb提供了一个重命名列名的选项,如下所示

db.collection.update({},{'$rename'=> {'old_name' => 'new_name'}}, false,true)

使用MongoMapper可以做同样的事情吗?文档没有指定任何内容。

我也试过从MongoMapper获取Mongodb连接句柄

connection = MongoMapper.connection 
db = MongoMapper.database
collection = db.collection('collection_name')
collection .update(....)

并执行相同的查询,但不起作用。

1 个答案:

答案 0 :(得分:1)

MongoMapper使用10gen Ruby驱动程序,MongoMapper :: Document提供对底层驱动程序对象的访问。

以下工作测试表明,您可以使用Model.collection.update执行所需操作,重命名模型“Model”的字段。请务必使用:multi =>如果要更新/重命名多个文档,则更新为true。

应用程序/模型/ model.rb

class Model
  include MongoMapper::Document
end

测试/单元/ model_test.rb

require 'test_helper'

class ModelTest < ActiveSupport::TestCase
  def setup
    Model.remove
  end

  test "rename" do
    puts "Model.collection.class: #{Model.collection.class}"
    puts "Model.database.class: #{Model.database.class}"
    Model.create( 'old_name' => 'name value 0', 'another_key' => 'another value 0' )
    Model.create( 'old_name' => 'name value 1', 'another_key' => 'another value 1' )
    assert_equal(2, Model.where( 'old_name' => { '$exists' => true } ).count)
    Model.collection.update( {}, { '$rename' => { 'old_name' => 'new_name' } }, :multi => true )
    assert_equal(0, Model.where( 'old_name' => { '$exists' => true } ).count)
    p Model.all
  end
end

$ rake test

Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options: 

# Running tests:

Model.collection.class: Mongo::Collection
Model.database.class: Mongo::DB
[DEPRECATED] The 'safe' write concern option has been deprecated in favor of 'w'.
[#<Model _id: BSON::ObjectId('5101809d7f11ba1256000001'), another_key: "another value 0", new_name: "name value 0">, #<Model _id: BSON::ObjectId('5101809d7f11ba1256000002'), another_key: "another value 1", new_name: "name value 1">]
.

Finished tests in 0.012344s, 81.0110 tests/s, 162.0220 assertions/s.

1 tests, 2 assertions, 0 failures, 0 errors, 0 skips