当有自定义_id时,mongo-ruby-driver不会在upsert上创建新文档

joh*_*ees 3 ruby ruby-on-rails mongodb

我想使用mongo-ruby-driver使用类似下面的内容来插入文档 -

id = "#{params[:id]}:#{Time.now.strftime("%y%m%d")}"
# db.collection('metrics').insert({'_id' => id})
db.collection('metrics').update(
  { '_id' => id },
  { '$inc' => { "hits" => 1 } },
  { 'upsert' => true }
)
Run Code Online (Sandbox Code Playgroud)

现在,这只会更新现有文档,如果尚不存在,则不会创建一个文档.它将执行这两个操作的唯一方法是,如果我取消注释它上面的insert()命令.

如果我使用mongo控制台并尝试直接执行此操作(不需要insert()),它将按预期工作.

Ser*_*sev 10

你应该在params中使用符号而不是字符串.这段代码有效.

db.collection('metrics').update(
  { '_id' => id },
  { '$inc' => { "hits" => 1 } },
  { :upsert => true }
)
Run Code Online (Sandbox Code Playgroud)

事实上,你可以在任何地方使用符号.这也有效:

db.collection(:metrics).update(
  { :_id => id },
  { :$inc => { :hits => 1 } },
  { :upsert => true }
)
Run Code Online (Sandbox Code Playgroud)