想象一下有一個帶有這個“模式”的 MongoDB 集合:
mycollection: {
name: String
treatments: [{
type: ObjectId,
colors: ObjectId[]
}]
}
并有幾條這樣的記錄
{
name: "Foo",
treatments:[
{ type: ObjectId('123456'), colors: [ObjectId('654321')] }
]
},
{
name: "Bar",
treatments:[
{ type: ObjectId('123456'), colors: [ObjectId('789012')] }
]
}
如果我嘗試使用以下方法過濾這些記錄:
{ "treatments.type": ObjectId('123456'), "treatments.colors": { $in: [ObjectId('654321')] } }
我希望只回傳名稱為“Foo”的記錄,但它會回傳兩條記錄,將過濾器視為 OR。甚至
{ $and: [{ "treatments.type": ObjectId('123456') }, { "treatments.colors": { $in: [ObjectId('654321')] } ] }
回傳相同。
任何幫助或澄清將不勝感激??
uj5u.com熱心網友回復:
在這種情況下,您需要在 mongodb 中使用 elemMatch 這將從陣列中找到同時滿足條件為真的元素
{ treatments: { $elemMatch: { type: ObjectId('123456'), colors: { $in: [ObjectId('654321')] } } } }
否則,mongodb 中的默認行為是,在對嵌套在檔案陣列中的多個欄位指定條件時,您可以指定查詢,以便單個檔案滿足這些條件或檔案中的任何檔案組合(包括單個檔案)陣列滿足條件。檢查此鏈接以獲取進一步說明https://docs.mongodb.com/manual/tutorial/query-array-of-documents/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414134.html
標籤:
