我有一个MongoDB集合,其文档结构类似于:
{
"_id" : "xxx",
"inner : {
"foo" : 1,
"bar" : 2
}
}数据库版本为4.2.6
还有一个聚合管道,其倒数第二个阶段是$project,其结果文档与以下类似的内容相匹配:
{
"_id" : "xxx",
"inner : {
"baz" : 3
}
}然后是合并到集合中的最后阶段:
{
"$merge" : {
into: "myCollection",
on: "_id",
whenMatched: "merge",
whenNotMatched: "discard"
}
}但是,结果是,现有的inner文档字段将被$merge结果覆盖。意思:
预期成果:
{
"_id" : "xxx",
"inner : {
"foo" : 1,
"bar" : 2,
"baz" : 3
}
}实际结果:
{
"_id" : "xxx",
"inner : {
"baz" : 3
}
}我怎样才能克服这一切?
发布于 2021-10-16 12:35:51
"merge“选项合并根文档,因此在查询中替换inner字段。
尝试用使用管道的合并替换合并。
我还没有测试过它,但我想它会没事的。
$$new变量是mongo定义的,用于引用来自管道的文档。
{
"$merge" : {
into: "myCollection",
on: "_id",
whenMatched:
[{"$project":
{"_id": "$_id",
"inner": {"$mergeObjects": ["$inner","$$new.inner"]}}}],
whenNotMatched: "discard"
}
}发布于 2021-10-16 19:59:53
接受的答案是一个很好的线索,尽管$project管道导致了除_id和inner之外的所有字段都被覆盖。这当然不是我想要的。
最明显的选择应该是简单地使用$addFields:
whenMatched: [
{"$addFields" :
{"inner.baz": "$$new.baz"}
}
]https://stackoverflow.com/questions/69595357
复制相似问题