簡體   English   中英

根據另一個集合字段值設置一個 MongoDB 集合字段值

[英]Set the a MongoDB collection field value based on another collection field value

我有 2 個 collections 像這樣:

//collection1
[{
    Name: 'abc'
},
{
    Name: 'def'
}]

// collection2
[{
    Name: 'abc'
    PresentInCollection1: '' // this field should be true since collection2.Name exists in collection1.Name
},
{
    Name: 'xyz'
    PresentInCollection1: '' // this field should be false since collection2.Name does not exists in collection1.Name
}]

collection2.Name collection1.Name時,我想將值collection2.PresentInCollection1 $set為 true 。 這是我嘗試過的:

db.stocks.update({}, [{
    $lookup: {
      from: 'collection1',
      localField: 'Name',
      foreignField: 'Name',
      as: 'Match',
    },
  },
  {
    $set: {
      PresentInCollection1: {
        $cond: [{
            $eq: ["Name", "$Match.Name"]
          },
          true,
          false
        ]
      },
    },
  },
]);

它拋出錯誤:

"$lookup is not allowed to be used within an update"

另一種方法是迭代更新文檔,但我想在 go 中執行此操作。 我正在考慮 MongoDB 的$map - $reduce但無法想到查詢:)

我會嘗試使用 $addFields 階段而不是 $set。 您基本上會在另一個集合中執行查找,然后您會想要添加一個指定“匹配”數組長度的字段。 然后,您將執行另一個 $addFields 階段並添加所需的“PresentInCollection1”字段,如果數組的大小大於 0,則將其設置為 true。如果數組的大小小於或等於 0,則將其設置為等於為假。

像這樣的東西(對不起,如果格式錯誤,我無權訪問格式化程序或代碼編輯器):

db.stocks.aggregate([{
    $lookup: {
      from: 'collection1',
      localField: 'Name',
      foreignField: 'Name',
      as: 'Match',
    },
  },
  {'$addFields': {
      'matchLen': {'$size': '$Match'}
    }
  },
 {'$addFields': {
     PresentInCollection1 : {'$cond':{ 
       'if': {$gt: ['$matchLen', 0]},
       'then': true,
       'else': false
        }
      }
    }
  },
 {'$unset': 'matchLen'}
]);

如果您希望文檔出現在新集合中,您還需要最后使用 out 階段。 (我沒有包括它,因為我不確定你是否需要它)

有人可能會找到更好的解決方案,但這只是我馬上想到的。

暫無
暫無

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

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