Ruby mongo:无法使用原子操作递增整数字段
我无法运行命令来增加 mongo DB 中的整数计数器。该命令在 mongo shell 中运行得很好。
所以这里是示例程序:
require 'rubygems'
require 'mongo'
# create sample mongo local DB
db = Mongo::Connection.new.db("dbtest")
# create sample mongo collection within DB
mytable = db.collection("tabletest")
# inserting some records into sample collection
mytable.insert({'name'=>'apple','mycnt'=>0})
mytable.insert({'name'=>'orange','mycnt'=>0})
mytable.insert({'name'=>'pear','mycnt'=>0})
######## following statement throws error
######syntax error, unexpected '}', expecting $end
mytable.update({"name": "apple"},{"$inc": {"mycnt": 1}})
当作为正常的 ruby 程序(不是 mongo shell)运行时,我不确定最后一个语句在语法方面有什么问题。非常感谢任何帮助。 mongo shell 中的类似命令运行良好,如下所示:
# db.tabletest.update({name: "apple"},{$inc: {mycnt: 1}})
I am unable to run a command the increment a integer counter in mongo DB. The command though works in mongo shell just fine.
So here the sample program:
require 'rubygems'
require 'mongo'
# create sample mongo local DB
db = Mongo::Connection.new.db("dbtest")
# create sample mongo collection within DB
mytable = db.collection("tabletest")
# inserting some records into sample collection
mytable.insert({'name'=>'apple','mycnt'=>0})
mytable.insert({'name'=>'orange','mycnt'=>0})
mytable.insert({'name'=>'pear','mycnt'=>0})
######## following statement throws error
######syntax error, unexpected '}', expecting $end
mytable.update({"name": "apple"},{"$inc": {"mycnt": 1}})
I am not sure what is wrong in the last statement in terms of syntax when running as normal ruby program (not mongo shell). Any help is greatly appreciated. Similar command in mongo shell works fine, which looks like following:
# db.tabletest.update({name: "apple"},{$inc: {mycnt: 1}})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
新样式的 JSONish Hash 语法仅适用于作为键的符号,您尝试将其与字符串一起使用。此外,
$inc:
将被视为全局变量$inc
后跟一个冒号,因此当您想要使用$inc
时,您不能使用 JSONish 语法>:$inc 符号作为键。请改用 hashrocket 语法:The new style JSONish Hash syntax only works with symbols as the keys, you're trying to use it with strings. Also, the
$inc:
will be seen as the global variable$inc
followed by a colon so you can't use the JSONish syntax when you want to use the:$inc
symbol as a key. Use the hashrocket syntax instead: