[英]Add new field To collection in MongoDB but the value based on value in another field
[英]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.