鑒于這些檔案:
{
"sections" : [
{
"name" : "section 1",
"questions" : [
{"q" : "color", "a" : "black"},
{"q" : "size", "a" : "large"}
]
}
]
}
和
{
"sections" : [
{
"name" : "section 1",
"questions" : [
{"q" : "color", "a" : "white"},
{"q" : "size", "a" : "large"}
]
},
{
"name" : "section 2",
"questions" : [
{"q" : "color", "a" : "black"},
{"q" : "size", "a" : "small"}
]
}
]
}
我如何為問題(q)“顏色”被回答(a)以“b”開頭并且問題“大小”在同一部分用“大”回答的檔案撰寫查詢?
我希望下面的查詢可以解決問題,并且只匹配第一個檔案 - 但它同時匹配:-(
{
sections: {
$elemMatch: {
questions: {
$elemMatch: {
"q" : "color",
"a" : {$regex: "^b.*"}
},
$elemMatch: {
"q" : "size",
"a" : "large"
}
}
}
}
}
到目前為止,我找到的唯一解決方案是使用聚合管道 $unwind'ing 部分,但是之后我需要重建原始檔案,而且我還沒有找到這樣做的好方法。
uj5u.com熱心網友回復:
詢問
- 2 個嵌套過濾器
- 嵌套的檢查是否
and color="^b.*" (starting with b), size="large" - 外部過濾器檢查嵌套過濾器是否回傳空結果
- 如果嵌套沒有回傳空結果檔案通過
*也許有一個宣告性較小的查詢,但這也可以
測驗代碼在這里
aggregate(
[{"$match":
{"$expr":
{"$ne":
[{"$filter":
{"input": "$sections.questions",
"cond":
{"$and":
[{"$in": [{"q": "size", "a": "large"}, "$$this"]},
{"$ne":
[{"$filter":
{"input": "$$this",
"cond":
{"$and":
[{"$eq": ["$$t.q", "color"]},
{"$regexMatch": {"input": "$$t.a", "regex": "^b.*"}}]},
"as": "t"}},
[]]}]}}},
[]]}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314289.html
