簡體   English   中英

如何檢查一個集合中的鍵值對是否匹配並使用 python 更新另一個 mongodb 集合中存在的鍵中的值

[英]How to check if a key value pair is matching in one collection and update the value in the key present in another mongodb collection using python

收藏一:

username:"abc123"

收藏2:

username:"abc123"
_id:ObjectId("5e78c5794f1f2d69b2a08139")

如果集合 1 和集合 2 中的“用戶名”匹配,我應該能夠從集合 2 復制“_id”並將新鍵和值插入為“代理:

ObjectId("5e78c5794f1f2d69b2a08139"

聚合可以做到這一點。

在集合 2 上運行聚合:

  • $lookup與 Collection 1 匹配
  • $unwind查找結果,它應該消除任何沒有找到匹配的結果
  • $addFields將代理字段添加到查找的文檔中
  • $replaceRoot使每個文檔的根成為從 Collection 1 中檢索到的那個,現在包含一個代理
  • $merge將管道中的文檔與 Collection 1 合並
db.getCollection("Collection 2").aggregate([
    {$lookup: {
               from: "Collection 1",
               localField: "username",
               foreignField: "username",
               as: "lookedup"
    }},
    {$unwind: "$lookedup"},
    {$addFields: {
            "lookedup.agent": "$_id"
    }},
    {$replaceRoot: {newRoot: "$lookedup"}},
    {$merge: "Collection 1"}
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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