简体   繁体   English

MONGODB updateMany 使用聚合管道和 $lookups

[英]MONGODB updateMany using aggregation pipeline and $lookups

I have to update the column "AcquireMerchant.Gateway" from Merchants collection but to get the exact amount of records that I have to update it needs to do two lookups with Banks collection and Institution collection.我必须从 Merchants 集合中更新“AcquireMerchant.Gateway”列,但要获得我必须更新的确切记录数量,需要对 Banks 集合和 Institution 集合进行两次查找。

This is the query that im working on but doesnt work.这是我正在处理但不起作用的查询。

The problem is when it execute the forEach I got this error "cannot compare to undefined".问题是当它执行 forEach 时,我收到此错误“无法与未定义进行比较”。 The aggregation works perfect聚合效果完美

db.getCollection("Merchants_INFRADB1230").aggregate( 
[
  {
    "$project": {
      "Merchants_INFRADB1230": "$$ROOT",
      "_id": 0
    }
  },
  {
    "$lookup": {
      "as": "Banks",
      "foreignField": "_id",
      "from": "Banks",
      "localField": "Merchants_INFRADB1230.SellingBankId"
    }
  },
  {
    "$unwind": {
      "path": "$Banks",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "as": "Institutions",
      "foreignField": "_id",
      "from": "Institutions",
      "localField": "Banks.InstitutionId"
    }
  },
  {
    "$unwind": {
      "path": "$Institutions",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$match": {
      "Institutions.GlobalId": "51a45baf-2538-4974-968e-4fb8bc86af95",
      "Merchants_INFRADB1230.AcquireMerchant.Gateway": "Update1"
    }
  },
  {
    "$project": {
      "Institutions.GlobalId": 1,
      "Merchants_INFRADB1230.AcquireMerchant.Gateway": 1,
      "Merchants_INFRADB1230.MID": 1
    }
  }
]).forEach(doc => db.Merchants_INFRADB1230.updateMany(
       { _id: doc._id },
       { $set: { "Merchants_INFRADB1230.AcquireMerchant.Gateway": "Update2"}}));

The aggregation returns documents with 3 fields (you explicitly removed _id):聚合返回具有 3 个字段的文档(您明确删除了 _id):

"Institutions.GlobalId"
"Merchants_INFRADB1230.AcquireMerchant.Gateway"
"Merchants_INFRADB1230.MID"

So in the forEach , the doc object will have only those fields, and doc._id will be undefined, which would make the filter {_id:doc._id} not match anything, if it were allowed to be undefined.所以在forEachdoc对象将只有这些字段,并且doc._id将是未定义的,如果允许未定义,这将使过滤器{_id:doc._id}不匹配任何内容。

The field "Merchants_INFRADB1230" was created in the aggregation, and so doesn't exist in the documents in the collection, so the update operation should probably be referring to the field as it exists in those documents:字段"Merchants_INFRADB1230"是在聚合中创建的,因此不存在于集合中的文档中,因此更新操作可能应该引用这些文档中存在的字段:

{ $set: { "AcquireMerchant.Gateway": "Update2"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM