How to query MongoDB directly from Ruby instead of using Mongoid?

If you’re using Mongoid 3, it provides easy access to its MongoDB driver: Moped. Here’s an example of accessing some raw data without using Models to access the data:

db = Mongoid::Sessions.default

# inserting a new document
collection = db[:collection_name]
collection.insert(name: 'my new document')

# finding a document
doc = collection.find(name: 'my new document').first

# iterating over all documents in a collection
collection.find.each do |document|
  puts document.inspect
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)