trnc
trnc

Reputation: 21587

Get embedded elements based on condition with mongoid

i use rails and mongodb (mongoid gem). i need to create a select form with specific elements which are embedded in a document. the document looks like this:

App --> Order --> Package

I want to get just the app-documents where package has a specific value. any advice how to achieve this? I tried the following way, but doesn't work:

@apps = current_user.apps.order.all(conditions: { order.package: 2 } )

Upvotes: 3

Views: 1931

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Check out this question: Mongoid / Mongodb and querying embedded documents

In your case:

@apps = App.where("orders.packages.name" => "supper").all

A way to test in the mongo shell:

app = {name:"yo"}
app.orders = []
order = {name:"1"}
order.packages = []
package = {name:"supper"}
order.packages.push package
app.orders.push(order)
db.apps.save(app)
db.apps.find()

# { "_id" : ObjectId("4dd288f139ead04b2cde11a6"), "name" : "yo", "orders" : [ { "name" : "1", "packages" : [ { "name" : "supper" } ] } ] }

db.apps.find({"orders.packages.name":"supper"});
{ "_id" : ObjectId("4dd288f139ead04b2cde11a6"), "name" : "yo", "orders" : [ { "name" : "1", "packages" : [ { "name" : "supper" } ] } ] }

Upvotes: 6

Related Questions