开发者

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.orde开发者_高级运维r.all(conditions: { order.package: 2 } )


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" } ] } ] }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜