【问题标题】:Set the a MongoDB collection field value based on another collection field value根据另一个集合字段值设置一个 MongoDB 集合字段值
【发布时间】:2020-07-24 00:29:26
【问题描述】:

我有 2 个这样的收藏:

//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.Namecollection1.Name 匹配时,我想将$set 的值collection2.PresentInCollection1 设置为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"

另一种方法是updating documents iteratively,但我想一次性完成。我正在考虑 MongoDB 的 $map - $reduce 但无法想到查询:)

【问题讨论】:

  • 我怀疑这是否可行,因为要使查找工作,您需要将 collection1 记录的 objectid 存储在 collection2 中。可能有另一种选择,首先查询一个集合并基于该更新另一个。让我知道这是否对你有用,我会发布我的答案。
  • @ShreeramK $map - $reduce 会做吗?我已经用iteratively updating documents approach 更新了这个问题,但还有更好的方法吗?

标签: mongodb


【解决方案1】:

我会尝试使用 $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 阶段。 (我没有包括它,因为我不确定你是否需要它)

也许有人能找到更好的解决方案,但这只是我马上想到的。

【讨论】:

  • 错误:“$lookup 不允许在更新中使用”
  • 当然可以。我错过了,我认为这是一个聚合,这就是为什么我将关于郊游的声明包含在一个集合中。我将编辑我的答案。谢谢。
猜你喜欢
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 2023-01-10
相关资源
最近更新 更多