假設我有這樣的模型
class Band
include Mongoid::Document
embeds_many :albums
end
class Album
include Mongoid::Document
field :name, type: String
field :producer, type: String
embedded_in :band
end
我想要的是所有專輯都由“喬治·馬丁”制作的樂隊。
我嘗試過,Band.where('albums.producer' => 'George Martin')但它匹配所有至少有一次 George Martin 制作人的樂隊。
例子:
這個樂隊應該匹配(因為他們所有的專輯都是由 George Martin 制作的):
{
"_id" : ObjectId("blabla"),
"albums" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"name" : "Violator",
"producer" : "George Martin"
}
]
}
這個樂隊不應該匹配(因為專輯“ ”是由另一位制作人制作的):
{
"_id" : ObjectId("blablabla"),
"albums" : [
{
"_id" : ObjectId("album1"),
"name" : "/",
"producer" : "George Martin"
},
{
"_id" : ObjectId("album2"),
"name" : " ",
"producer" : "Another producer"
}
]
}
uj5u.com熱心網友回復:
您可以使用$reduce來處理您的albums陣列。通過設定初始值true,您可以false通過將$and條件與累加器一起使用,有條件地將值設定為當一個條目不等于“喬治馬丁”時。$match累加器執行過濾的最終結果。
{
"$reduce": {
"input": "$albums",
"initialValue": true,
"in": {
$and: [
"$$value",
{
$eq: [
"$$this.producer",
"George Martin"
]
}
]
}
}
}
這是Mongo 游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329207.html
