arrays - 如何覆盖当前文档 mongodb
问题描述
我有这个聚合命令,需要覆盖当前文档;
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
}
])
Collection:
{
id:...
class:"Apples"
imageUrl:"..."
}
有多个文档需要更新。这是我目前附加到上述命令的内容,但它不起作用。
.forEach( doc => db.product.updateOne( { _id: doc._id }, { $set: { imageUrl: doc.imageUrl } } ) )
提前致谢!
解决方案
您可以运行$out(用聚合结果替换整个现有集合):
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
},
{ $out: "collection" }
])
或新的$merge运算符(“合并”聚合结果与现有文档):
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
},
{ $merge: { into: "collection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])
推荐阅读
- hover - Vala:无法让 enter_notify_event 正常工作
- python - 根据环比计算同比增长率
- sql - 基于嵌套 JSON 创建数据库
- node.js - 将 jsonp 集成到 Flask 服务器时返回 500 错误
- nginx - nginx connect() 到 ip:80 失败(99:地址不可用)
- java - 错误-使用 tomcat 构建 maven java servlet 项目
- javascript - 有没有办法在使用多个 useState 时简化条件渲染?
- html - 有没有办法为元素及其伪元素应用精神动画?
- postgresql - 字符和数字混合时的自然排序
- java - 数组转换为浮动和加倍