gpt4 book ai didi

ruby-on-rails - Mongoid:选择适合多个选项的嵌入对象

转载 作者:可可西里 更新时间:2023-11-01 09:11:51 26 4
gpt4 key购买 nike

我有这个结构

class House
include Mongoid::Document
embeds_many :inhabitants
end

class Inhabitant
include Mongoid::Document
embedded_in :house
field :name
field :gender
field :age
end

我可以得到所有女性居住的房子:

houses = House.where("inhabitants.gender" => "female")

但是我怎样才能得到所有 50 岁以下女性居住的房子呢?如何为嵌入对象指定多个条件?

最佳答案

要对数组中的每个条目应用多个条件,您应该使用 $elemMatch 运算符。我不熟悉 Mongoid,但这里是修改为使用 $elemMatch 的查询的 MongoDB shell 语法:

> db.house.find({inhabitants: {$elemMatch: {gender: "female", age: {$lt: 50}}}})

关于ruby-on-rails - Mongoid:选择适合多个选项的嵌入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7389539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com