簡體   English   中英

MongoDB 使用來自一個 Collection 的 ID 數組根據來自另一個 Collection 的 ID 過濾結果

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM