使用不同的密钥进行Mongoid upsert

时间:2012-07-01 10:25:13

标签: ruby-on-rails mongodb mongoid upsert database

是否可以使用JSON /字段哈希插入mongodb集合,但不使用_id ObjectId字段,而是使用其他索引字段,例如external_id

我用它来更新我每天从Feed收到的一些项目,因此,Feed项目不包含我的内部ID。

1 个答案:

答案 0 :(得分:1)

是的,可以在Mongoid中使用自定义ID进行升级,但仅限于2012年6月27日左右的3.0.0.rc。

应用程序/模型/ 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