3

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 } )
Clifford
  • 88,407
  • 13
  • 85
  • 165
trnc
  • 20,581
  • 21
  • 60
  • 98

1 Answers1

6

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" } ] } ] }
Community
  • 1
  • 1
Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109