I'd like to use t开发者_如何学Pythonhe addToSet method of MongoDB, but Mongoid doesn't currently support this yet. Is there a way of directly accessing the MongoDB driver from my Rails model?
I asked this question on Mongoid group and this was the best response:
Assuming your model object is a Mongoid::Document, simply call the "db" method on it to get a handle to the Mongo::DB object that Mongoid is using under the hood.
http://rdoc.info/github/mongoid/mongoid/master/Mongoid/Collections/Cl...
From there, you can use the MongoDB Ruby driver API directly.
http://api.mongodb.org/ruby/current/file.TUTORIAL.html#
Also, you can access the record collection using ModelName.collection.
You can use the mongo-ruby-driver gem from mongodb:
https://github.com/mongodb/mongo-ruby-driver
Check the update method in the api:
http://api.mongodb.org/ruby/1.2.0/Mongo/Collection.html#update-instance_method
And this option might be what you're looking for to use addToSet:
(Boolean) :upsert — default: +false+ — if true, performs an upsert (update or insert)
Up to and including Mongoid 2.4 you could access the database object with
db = Mongoid.master
精彩评论