2016-11-11 87 views
0

ALL $我有一個這樣的數組:貓鼬數組元素的數組

{ 
    "_id" : ObjectId("581b7d650949a5204e0a6e9b"), 
    "types" : [ 
     { 
      "type" : ObjectId("581b7c645057c4602f48627f"), 
      "quantity" : 4, 
      "_id" : ObjectId("581b7d650949a5204e0a6e9e") 
     }, 
     { 
      "type" : ObjectId("581ca0e75b1e3058521a6d8c"), 
      "quantity" : 4, 
      "_id" : ObjectId("581b7d650949a5204e0a6e9e") 
     } 
    ], 
    "__v" : 0 
}, 
{ 
    "_id" : ObjectId("581b7d650949a5204e0a6e9c"), 
    "types" : [ 
     { 
      "type" : ObjectId("581b7c645057c4602f48627f"), 
      "quantity" : 4, 
      "_id" : ObjectId("581b7d650949a5204e0a6e9e") 
     } 
    ], 
    "__v" : 0 
} 

我想創建一個查詢,將返回我elementswhere類型的陣列中的所有匹配數組$。

例如:

query([ObjectId("581b7c645057c4602f48627f"), ObjectId("581ca0e75b1e3058521a6d8c")]) 

應該返回元件1和2

query([ObjectId("581b7c645057c4602f48627f")]) 

應該返回元件2

query([ObjectId("581ca0e75b1e3058521a6d8c")]) 

應返回任何

我試圖

db.getCollection('elements').find({'types.type': { $in: [ObjectId("581ca0e75b1e3058521a6d8c")]}}) 

但是,如果只有一個類型的匹配

+0

why query [[ObjectId(「581ca0e75b1e3058521a6d8c」)])should not nothing nothing? –

+0

因爲沒有元素只有ObjectId類型(「581ca0e75b1e3058521a6d8c」) – Leamas

回答

1

您可能需要使用聚合爲$在和$ elematch只會返回匹配的元素,它返回的元素。項目階段設置爲等於創建全部匹配標誌並在最後階段與真實值匹配。

aggregate([ { 
    $project: { 
     _id: 0, 
     isAllMatch: {$setIsSubset: ["$types.type", [ObjectId("581b7c645057c4602f48627f")]]}, 
     data: "$$ROOT" 
    } 
}, { 
    $match: { 
     isAllMatch: true 
    } 
}]) 

樣本輸出

{ 
    "isAllMatch": true, 
    "data": { 
     "_id": ObjectId("581b7d650949a5204e0a6e9c"), 
     "types": [{ 
      "type": ObjectId("581b7c645057c4602f48627f"), 
      "quantity": 4, 
      "_id": ObjectId("581b7d650949a5204e0a6e9e") 
     }], 
     "__v": 0 
    } 
} 

替代版本:

這個版本結合了項目和比賽階段進入一個$纂與$ COND運營階段,以決定是否保留或修剪的元素。

aggregate([{ 
    "$redact": { 
     "$cond": [{ 
       $setIsSubset: ["$types.type", [ObjectId("581b7c645057c4602f48627f")]] 
      }, 
      "$$KEEP", 
      "$$PRUNE" 
     ] 
    } 
}]) 
+0

我想返回元素,而不是類型。 我認爲$ setEquals將無法正常工作,因爲我想驗證元素中的所有類型是否都在作爲參數給出的數組中。 – Leamas

+0

它正在返回具有類型的元素。您可以將任何數組傳遞給組管道中的isAllMatch。請更新您的帖子,確切地說您想查看您輸入的內容和輸入。 – Veeram

+0

感謝您的回覆。 $ setEquals:['$ types.type',myTypes]似乎沒有做這項工作。 只有'$ types.type'與myTypes的元素相同纔是真的。 如果$ types.type中的所有元素都在myTypes中,我希望它是真的。 如果$ types.type = [1,2]和myTypes = [1,2,3]我想返回元素。現在,它不返回 – Leamas