我正在使用具有以下資料的集合名稱“歷史”
[
{
"_id": {
"$oid": "634a9d1b269c99e9364e8750"
},
"marks": [
{
"results": [
{
"product": "Abc",
"score": 55
}
]
}
]
},
{
"_id": {
"$oid": "634a9fae269c99e9364e8755"
},
"marks": [
{
"results": [
{
"product": "Abc",
"score": 10
},
{
"product": "Xyz",
"score": 5
}
]
}
]
},
{
"_id": {
"$oid": "634a9fae269c99e9364e8756"
},
"marks": [
{
"results": [
{
"product": "Abc",
"score": 8
},
{
"product": "Xyz",
"score": 7
}
]
}
]
},
{
"_id": {
"$oid": "634a9fae269c99e9364e8757"
},
"marks": [
{
"results": [
{
"product": "Abc",
"score": 7
},
{
"product": "Xyz",
"score": 8
}
]
}
]
}
]
我的 Fetch 命令是這個..
db.History.findOne({"marks.results.product":"Xyz"})
命令執行沒有錯誤,但它顯示錯誤的結果..
{
"_id": {
"$oid": "634a9fae269c99e9364e8755"
},
"marks": [
{
"results": [
{
"product": "Abc",
"score": 10
},
{
"product": "Xyz",
"score": 5
}
]
}
]
}
結果中的第一個物件(產品:“Abc”)不應顯示為不符合標準(Product="Xyz")請糾正我并指導我如何獲取所需的資料(物件僅符合標準,即 Product="Xyz" )
uj5u.com熱心網友回復:
您在此處的示例資料是一個包含 4 個檔案的集合。其中 3 個包含product="Xyz"與其他產品一起。findOne找到其中包含的一個檔案product="Xyz",并按原樣回傳該檔案(不對其進行操作)。您要求的是僅取回檔案的一部分 - 這意味著您想要results在回傳的答案中操作(雙)嵌套陣列。您可以使用聚合管道來完成。
一種選擇是$unwind用于此
db.collection.aggregate([
{$match: {"marks.results.product": "Xyz"}},
{$limit: 1} // if you want only one document to return
{$unwind: "$marks"},
{$unwind: "$marks.results"},
{$match: {"marks.results.product": "Xyz"}}
])
看看它在操場上的例子是如何作業的 - 放松
另一種選擇是$map和$filter:
看看它在操場上的例子是如何作業的 - 過濾器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514911.html
上一篇:C 試圖創建二維點(陣列)的佇列
