ruby mongodb驱动程序推送到阵列

时间:2014-07-30 15:48:40

标签: ruby mongodb mongodb-ruby

假设我有一份文件Person,我希望将Tags添加到此文档中。

所以我希望文档看起来像

{ "_id" : 5,
  "tags" : ["Music", "Baseball", "Skiing"]
}

每次有人选择兴趣时,我都想将其附加到tags列表。

这是我的尝试:

require 'mongo'

client = Mongo::Connection.new
db     = client['some_app']
coll   = db['persons']
coll.update({_id: 5}, {"$push" => {tags: "PS4"}}, {upsert: true}) 

如果我运行这个,我会得到一个例外:

/usr/local/rvm/gems/ruby-2.1.2/gems/bson-1.10.2/lib/bson/bson_c.rb:20:in `serialize': key $push must not start with '$' (BSON::InvalidKeyName)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

对我来说很好看,对我有用。以下更详尽的测试对我有用,请看看它是否适合您,它应该有助于澄清您的问题,我怀疑您在发布时丢失了。

test_unit.rb:

require 'mongo'
require 'test/unit'
require 'json'

class MyTest < Test::Unit::TestCase
  def setup
    @coll = Mongo::MongoClient.new['some_app']['persons']
    @coll.remove
  end

  test "BSON version" do
    assert_equal("1.10.2", CBson::VERSION, "confirm loading of C extension and version")
  end

  test "$push to existing doc" do
    json = %q{
      {
          "_id" : 5,
          "tags" : ["Music", "Baseball", "Skiing"]
      }
    }
    @coll.insert(JSON.parse(json))
    @coll.update({_id: 5}, {"$push" => {tags: "PS4"}}, {upsert: true})
    assert(@coll.find.to_a.first['tags'].include?('PS4'))
  end

  test "upsert and $push" do
    @coll.update({_id: 5}, {"$push" => {tags: "PS4"}}, {upsert: true})
    assert(@coll.find.to_a.first['tags'].include?('PS4'))
  end
end

ruby​​ -v test_unit.rb

ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin12.0]
osprey:free-59705-mongo-push gjm$ ruby test_unit.rb
Loaded suite test_unit
Started
...

    Finished in 0.019441 seconds.

3 tests, 3 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed

154.31 tests/s, 154.31 assertions/s