我試圖動態查詢,看起來像這樣一個數據庫:動態查詢從輸入對象
db.test.insert({
"_id" : ObjectId("58e574a768afb6085ec3a388"),
"place": "A",
"tests" : [
{
"name" : "1",
"thing" : "X",
"evaluation" : [
{
"_id": ObjectId("58f782fbbebac50d5b2ae558"),
"aHigh" : [1,2],
"aLow" : [ ],
"zHigh" : [ ],
"zLow" : [1,3]
},
{
"_id": ObjectId("58f78525bebac50d5b2ae5c9"),
"aHigh" : [1,4],
"aLow" : [2],
"zHigh" : [ 3],
"zLow" : [ ]
},
{
"_id": ObjectId("58f78695bebac50d5b2ae60e"),
"aHigh" : [ ],
"aLow" : [1,2,3],
"zHigh" : [1,2,3,4],
"zLow" : [ ]
},]
},
{
"name" : "1",
"thing" : "Y",
"evaluation" : [
{
"_id": ObjectId("58f78c37bebac50d5b2ae704"),
"aHigh" : [1,3],
"aLow" : [4],
"zHigh" : [ ],
"zLow" : [3]
},
{
"_id": ObjectId("58f79159bebac50d5b2ae75c"),
"aHigh" : [1,3,4],
"aLow" : [2],
"zHigh" : [2],
"zLow" : [ ]
},
{
"_id": ObjectId("58f79487bebac50d5b2ae7f1"),
"aHigh" : [1,2,3],
"aLow" : [ ],
"zHigh" : [ ],
"zLow" : [1,2,3,4]
},]
}
]
})
db.test.insert({
"_id" : ObjectId("58eba09e51f7f631dd24aa1c"),
"place": "B",
"tests" : [
{
"name" : "2",
"thing" : "Y",
"evaluation" : [
{
"_id": ObjectId("58f7879abebac50d5b2ae64f"),
"aHigh" : [2],
"aLow" : [3 ],
"zHigh" : [ ],
"zLow" : [1,2,3,4]
},
{
"_id": ObjectId("58f78ae1bebac50d5b2ae6db"),
"aHigh" : [ ],
"aLow" : [ ],
"zHigh" : [ ],
"zLow" : [3,4]
},
{
"_id": ObjectId("58f78ae1bebac50d5b2ae6dc"),
"aHigh" : [1,2],
"aLow" : [3,4],
"zHigh" : [ ],
"zLow" : [1,2,3,4]
},]
}
]
})
爲了查詢數據庫,我由我的程序的其他部分創建的對象。它有以下形式:
var outputObject = {
"top": {
"place": [
"A"
]
},
"testing": {
"tests": {
"name": [
"1",
],
"thing": [
"X",
"Y"
]
}
}
}
然後我用的是總框架內outputObject
和$match
語句來執行查詢。我已經包含了兩個似乎不起作用的查詢。
db.test.aggregate([
{$match: {outputObject.top}},
{$unwind: '$tests'},
{$match: {outputObject.testing}},
{$unwind: '$tests.evaluation'},
{$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
])
db.test.aggregate([
{$match: {$and: [outputObject.top]}},
{$unwind: '$tests'},
{$match: {$and: [outputObject.testing]}},
{$unwind: '$tests.evaluation'},
{$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
])
但是,這種方法似乎不起作用。我有幾個問題:
- 我需要把它應用到
$match
語句之前修改的對象outputObject
? - 我的查詢是否正確?
- 我是否應該使用
$and
或$in
結合$match
聲明? - 哪些代碼會產生所需的結果?
目前使用mongoDB 3.4.4
使用你的解決方案工作得很好,除非在頂部沒有值。例如,當'VAR outputObject = { 「測試」:{ 「測試」:{ 「名稱」:[ 「1」 ], 「東西」:[ 「X」, 「Y」 ] } } };'解決方案失敗。有沒有辦法使它的功能不管在頂部是否有東西? –
@ black_sheep07如果您實際閱讀內容,我會告訴您兩次,您需要單獨的「頂部」和「底部」部分的推定是不正確的,事實上,您需要條件才能應用最初和以後的過濾。我還記得以前跟你說過的話[當你對問題有不同的問題時,你可以單獨提問](https://stackoverflow.com/questions/ask)。 –
@ black_sheep07換句話說,這是一個「代碼中的單個語句」Object.assign(outputObject.top,outputObject.testing)'這是唯一引用我說你應該「擺脫」的兩個鍵因爲沒有必要讓他們在那裏。事實上,這個陳述所做的是通過將來自兩個鍵的結果「合併」爲單個文檔來「移除」這些鍵。 –