使用mongoid获取基于条件的嵌入元素

Tro*_*nic 3 ruby-on-rails mongodb mongoid

我使用rails和mongodb(mongoid gem).我需要创建一个包含特定元素的选择表单,这些元素嵌入在文档中.该文件如下:

App - > Order - > Package

我想获得包具有特定值的app-documents.任何建议如何实现这一目标?我尝试了以下方法,但不起作用:

@apps = current_user.apps.order.all(conditions: { order.package: 2 } )
Run Code Online (Sandbox Code Playgroud)

Jes*_*ott 6

看看这个问题:Mongoid/Mongodb并查询嵌入式文档

在你的情况下:

@apps = App.where("orders.packages.name" => "supper").all
Run Code Online (Sandbox Code Playgroud)

一种在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" } ] } ] }
Run Code Online (Sandbox Code Playgroud)