8

I'd like to use the 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?

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

looks like the db method is out and the collection method is in!
0

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)

Comments

0

Up to and including Mongoid 2.4 you could access the database object with

db = Mongoid.master

1 Comment

This doesn't work with 3+. MyModel.collection.database, however, does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.