【发布时间】: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.Name 与collection1.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