I can't figure out how to do comparison queries with Nimongo. Would appreciate
any solutions.
import oids
import nimongo/bson ## MongoDB BSON serialization/deserialization
import nimongo/mongo ## MongoDB client
## Create new Mongo client
var m = newMongo()
## Connect to Mongo server
let connectResult = m.connect()
## Specify collection
let collection = m["db"]["weather"]
## Create new bson document
let weather_item = %*{
"_id": $genOid(),
"temp": 15.6,
"feels_like": 14.5,
"units": "C"
}
## Insert document into DB
collection.insert(weather_item)
## Fetch number of weather items
let num_wi = collection.find(%*{}).count()
echo "# of weather items: ", num_wi
# tried different variations of the query below, but still can't get the
correct behavior
let query = B("temp", "{$gt:10}".toBson)
echo query
let temps_over_10C = collection.find(query)
let tn = temps_over_10C.count()
echo "Found ", tn, " records with temp over 10C"
for temp in temps_over_10C:
echo "temp = ", temp
# Output:
# # of weather items: 4
# {
# "temp" : "{$gt:10}"
# }
# Found 0 records with temp over 10C
Run
The records are correctly inserted into mongo (from multiple runs). And I am
confident the find syntax is correct as the same command works from the mongo
shell:
> db.weather.find({"temp": {$gt:10}})
{ "_id" : "5cbf2625e269b85d096176b6", "temp" : 15.6, "feels_like" : 14.5,
"units" : "C" }
{ "_id" : "5cbf299d4fded4440a4531fe", "temp" : 15.6, "feels_like" : 14.5,
"units" : "C" }
Run
I suspect it has to do with additional double quotes being inserted into the
filter, but I am not sure how to force nimongo to do without them:
> db.weather.find({"temp": "{$gt:10}"}).count()
0
Run