2012-07-01 37 views
3

是否有可能使用JSON /哈希字段插入到MongoDB集合中,而不是使用_id ObjectId字段來使用不同的索引字段,如external_idMongoid upsert使用不同的密鑰

我正在使用它來更新從飼料每天收到的一些項目,因此飼料項目不包含我的內部標識。

回答

1

是的,有可能在Mongoid自定義ID來UPSERT,但只有在3.0.0.rc大約6月27日,2012年

應用程序/模型/ item.rb的

class Item 
    include Mongoid::Document 

    field :external_id, type: String 
    field :_id, type: String, default: ->{ external_id } 
    field :text, type: String 
end 

測試/單元/ item_test.rb

require 'test_helper' 

class ItemTest < ActiveSupport::TestCase 
    def setup 
    Item.delete_all 
    end 

    test "external id" do 
    Item.new(text: 'Lorem ipsum').upsert 
    Item.new(external_id: 'an external id', text: 'dolor sit amet').upsert 
    puts Item.all.to_a.collect{|item|item.inspect} 
    end 
end 

輸出

執行命令選項:--name = test_external_id

# Running tests: 

#<Item _id: 4ff202501f98ce8202c03268, _type: nil, external_id: nil, text: "Lorem ipsum"> 
#<Item _id: an external id, _type: nil, external_id: "an external id", text: "dolor sit amet"> 
. 

Finished tests in 0.028232s, 35.4208 tests/s, 0.0000 assertions/s. 

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

要做到這一點,你將不得不從GitHub,參觀和克隆從

https://github.com/mongoid/mongoid 

bundle install 
bundle exec rake install 

安裝下面就來提交,使這一切成爲可能的鏈接。

https://github.com/mongoid/mongoid/commit/3062363bad3ab947d7689502d6805652b20e89a0 
相關問題