1

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(....)

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

4

1 回答 1

1

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

以下工作测试表明您可以使用 Model.collection.update 来做您想做的事情,重命名模型“模型”的字段。如果要更新/重命名多个文档,请确保使用 :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

$耙子测试

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
于 2013-01-24T18:45:50.120 回答