有一个自定义

编程入门 行业动态 更新时间:2024-10-25 11:18:51
有一个自定义_id时,mongo-ruby-driver不会在upsert上创建一个新文档(mongo-ruby-driver will not create a new document on upsert when there is a custom _id)

我想用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 } )

更多推荐

本文发布于:2023-07-31 01:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   有一个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!