質問

I'm getting setup in mongodb, was looking into using the greater than hash parameter and I get an error. However, when I use a hashrocket it works. Why is this?

require 'rubygems'
require 'mongo'
require 'pry'
require 'win32ole'

db = Mongo::Connection.new.db("test")
x = db['text']

y = x.find({a: {$gt: 0}})
y.each {|y| puts y }

Data

{"_id"=>BSON::ObjectId('51630eea5a8d7b8a8be738c0'), "a"=>1.0}
{"_id"=>BSON::ObjectId('51632de8583be71698000001'), "a"=>1}
{"_id"=>BSON::ObjectId('51632de8583be71698000002'), "a"=>1, "b"=>2}

The Error

syntax error, unexpected ':', expecting tASSOC

for this line at the $gt: part y = x.find({a: {$gt: 0}})

This while

y = x.find({'b' =>  {'$gt' => 0}})
y.each {|y| puts y }
役に立ちましたか?

解決

I think that $gt is being interpreted as a reference to global variable $gt, not a symbol :$gt. And since you can't use colonized hash syntax with variables, it rightfully expects a hashrocket. The query should work with both string and symbol:

y = x.find({'b' =>  {'$gt' => 0}})
y = x.find({'b' =>  {:$gt => 0}})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top