[英]MongoDB using an array of IDs from one Collection to filter the results based on the IDs from another Collection
假設有一個 MongoDB Collection CollA
。 假設CollA
有以下三個 Document:
{"_id": "1", "name": "Bob"},
{"_id": "2", "name": "John"},
{"_id": "3", "name": "Will"}
假設有另一個 MongoDB Collection CollB
具有以下文檔:
{
"_id": "1",
"foo": {
"arr": ["1", "3"]
}
}
MongoDB 中是否有辦法查詢CollB
以獲取foo.arr
數組內容( ["1"],["3"]
)並使用它來檢索CollA
中具有這些_id
值的文檔,以產生以下結果:
{"_id": "1", "name": "Bob"},
{"_id": "3", "name": "Will"}
從CollB
執行簡單的$lookup
。 在$unwind
之后使用$replaceRoot
和$lookup
結果
db.CollB.aggregate([
{
"$lookup": {
"from": "CollA",
"localField": "foo.arr",
"foreignField": "_id",
"as": "collALookup"
}
},
{
"$unwind": "$collALookup"
},
{
"$replaceRoot": {
"newRoot": "$collALookup"
}
}
])
這是Mongo Playground供您參考。
詢問
foo.arr
和限制 1 查找_id
字段,我們只關心是否加入(無需將許多文檔保存到內存中) *這將使 collA 保留其_id
位於 collB 中的任何數組中的所有文檔(如果您只想要 collB 的 1 個特定文檔,我認為從 collB 開始,如 ray 的答案更有意義,但在$match
之前添加$lookup
collB 的 1 個成員)
collA.aggregate(
[{"$lookup":
{"from": "collB",
"localField": "_id",
"foreignField": "foo.arr",
"pipeline": [{"$limit": 1}],
"as": "results"}},
{"$match": {"$expr": {"$ne": ["$results", []]}}},
{"$unset": ["results"]}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.