简体   繁体   中英

Using upsert with push to an array option on Ruby driver

I'm trying to do an upsert with ruby driver to mongodb. If the row exist I wish to push new data to and array, else create new document with one item in the array.

When I run it on mongodb it looks like that:

db.events.update( { "_id" : ObjectId("4f0ef9171d41c85a1b000001")}, 
{ $push : { "events" : { "field_a" : 1 , "field_b" : "2"}}}, true)

And it works.

When I run it on ruby it looks like that:

@col_events.update( { "_id" => BSON::ObjectId.from_string("4f0ef9171d41c85a1b000001")}, 
{ :$push => { "events" => { "field_a" => 1 , "field_b" => "2"}}}, :$upsert=>true)

And it doesn't work. I don't get an error but I don't see new rows either.

Will appreciate the help in understanding what am I doing wrong.

So a couple of issues.

  1. In Ruby, the command should be :upsert=>true . Note that there is not $ . The docs for this are here .
  2. You are not running the query with :safe=>true . This means that some exceptions will not fire. So you could be causing an exception on the server, but you are not waiting for the server to acknowledge the write.

Just adding some code for Gates VP's excellent answer:

require 'rubygems'
require 'mongo'

@col_events = Mongo::Connection.new()['test']['events']

#safemode enabled
@col_events.update(
  { "_id" => BSON::ObjectId.from_string("4f0ef9171d41c85a1b000001")},
  { "$push" => { "events" => { "field_a" => 1, "field_b" => "2"}}},
  :upsert => true, :safe => true
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM