我想用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 } )现在,这只会更新现有的文档,而不会创建一个,如果它不存在。 它将执行这两个操作的唯一方法是如果我取消注释上面的insert()命令。
如果我使用mongo控制台并尝试直接执行这个upsert(不需要insert()),它可以按预期工作。
I want to upsert a document with the mongo-ruby-driver using something like the following-
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 } )Right now this will only update existing documents, and not create one if it doesn't already exist. The only way it will perform both actions is if I uncomment the insert() command above it.
If I use the mongo console and try and do this upsert directly (without the need for the insert() ) it works as expected.
最满意答案
您应该在params中使用符号而不是字符串。 此代码有效。
db.collection('metrics').update( { '_id' => id }, { '$inc' => { "hits" => 1 } }, { :upsert => true } )事实上,你可以在任何地方使用符号。 这也适用于:
db.collection(:metrics).update( { :_id => id }, { :$inc => { :hits => 1 } }, { :upsert => true } )You should use a symbol instead of string in params. This code works.
db.collection('metrics').update( { '_id' => id }, { '$inc' => { "hits" => 1 } }, { :upsert => true } )In fact, you can use symbols most everywhere. This also works:
db.collection(:metrics).update( { :_id => id }, { :$inc => { :hits => 1 } }, { :upsert => true } )更多推荐
发布评论