Mongoid / Mongodb and querying embedded documents

You can query embedded documents, just qualify the name. Now, this will return all Authors that have books that match your query. If Author is defined as having many :books (and book is an embedded::document) @authors_with_sewid = Author.where(“books.name” => “sewid”).all You’d then need to iterate over the authors and extract the books.

MongoDB – is DBREF necessary?

Dbref in my opinion should be avoided when work with mongodb, at least if you work with big systems that require scalability. As i know all drivers make additional request to load DBRef, so it’s not ‘join‘ within database, it is very expensive. Is there a way to reference other documents without having the somewhat … Read more

Find documents with array that doesn’t contains a specific value

Nothing wrong with what you are basically attempting, but perhaps the only clarification here is the common misconception that you need operators like $nin or $in when querying an array. Also you really need to do here is a basic inequality match with $ne: Person.find({ “groups”: { “$ne”: group._id } }) The “array” operators are … Read more

Unable to connect to mongoDB running in docker container

If you specified the correct port and still not able to connect to mongodb running in docker (like me), make sure you are using the service name (or container name) in your connection URL, e.g. mongodb://mongodb_service:27017/mydb, which is defined in your docker-compose.yml : services: mongodb_service: image: mongo I was using the hostname value and that’s … Read more

Mongodb group and sort

Inspired by this example on mongo’s website. GENERATE DUMMY DATA: > db.stack.insert({a:1,b:1,c:1,active:1}) > db.stack.insert({a:1,b:1,c:2,active:0}) > db.stack.insert({a:1,b:2,c:3,active:1}) > db.stack.insert({a:1,b:2,c:2,active:0}) > db.stack.insert({a:2,b:1,c:3,active:1}) > db.stack.insert({a:2,b:1,c:10,active:1}) > db.stack.insert({a:2,b:2,c:10,active:0}) > db.stack.insert({a:2,b:2,c:5,active:1}) MONGO QUERY: > db.stack.aggregate( … {$match:{active:1}}, … {$group:{_id:{a:”$a”, b:”$b”}, csum:{$sum:”$c”}}}, … {$sort:{“_id.a”:1}}) RESULT: {“result” : [ {“_id” : {“a” : 1,”b” : 2},”csum” : 3}, {“_id” : {“a” : … Read more