Is there a way to pass a BSON object directly into the .find() in the mongo-ruby-driver?
At the moment I have a basic sinatra app that takes URL encoded JSON and parses it into the .find() but I would ideally like to give it straight BSON:
require 'sinatra'
require 'mongo'
require 'json'
include Mongo
db = MongoClient.new().db('test')
get '/' do
if request[:query]
query = JSON.parse(CGI::unescape(request[:query]))
db.collection('test_collection').find(query).to_a.to_json
end
end
So essentially have something along the lines of BSON.parse(url-encoded-query) and be able to pass that into a .find() returning the result.
Example URL: http://localhost:4567/?query=%7B%20%22name%22%20%3A%20%22john%20doe%22%20%7D
Current query: { "name" : "john doe" }
BSON query: { name: /.*john.*/, interests: [ 'fishing', 'golf' ]} that I’d like to work
The following test script demonstrates how to use the $elemMatch operator as a projection. Please note that the Collection#find method takes arbitrary documents for both the “selector” formal parameter and for the “opts” :fields option.
MongoDB documents are mapped to/from Ruby Hash objects, and these documents can fully incorporate MongoDB operators.
elemmatch_projection.rb
ruby elemmatch_projection.rb
This is another answer because the question has been significantly clarified by the OP.
Hope that this helps you understand how to use MongoDB documents and operators in Ruby.