通过与 id[1602271] 匹配的第一个操作,它创建新集合并保存一个文档(下面提到的文档)。
{
"_id": "1602271",
"date": "2019-02-11T06:25:13.425Z",
"currentStatus": "scheduled",
"statusHistory": [
{
"status": "onboarded",
"date": "2018-11-02T10:07:11.167Z"
},
{
"status": "preference_ready",
"date": "2018-11-02T10:08:56.359Z"
},
{
"status": "scheduled",
"date": "2018-11-02T10:26:38.721Z"
}
]
}
对于第二个操作 id[1602131],它不会创建新文档,而是用旧文档覆盖(高于 JSON)。
{
"_id": "1602131",
"date": "2019-01-22T07:08:58.253Z",
"currentStatus": "scheduled",
"statusHistory": [
{
"status": "onboarded",
"date": "2018-11-02T06:07:28.765Z"
},
{
"status": "preference_ready",
"date": "2018-11-02T06:11:30.777Z"
},
{
"status": "scheduled",
"date": "2018-11-29T05:48:57.871Z"
}
]
}
请引用下面的代码:
public static final String STATUS_COLLECTION_NAME = "TeacherStatus";
public static final String ARCHIVE_STATUS_COLLECTION_NAME =
"ArchiveTeacherStatus";
Aggregation aggregation = Aggregation.newAggregation(match(where("_id").is(teacherId)),
out(ARCHIVE_STATUS_COLLECTION_NAME));
mongoOperations.aggregate(aggregation, STATUS_COLLECTION_NAME, TeacherStatus.class);
最佳答案
按预期工作。 https://docs.mongodb.com/manual/reference/operator/aggregation/out/
If the collection specified by the
$out
operation already exists, then upon completion of the aggregation, the$out
stage atomically replaces the existing collection with the new results collection.
在 mongodb 4.2 中,$out
阶段将接受一个附加参数 mode
,该参数可以采用值“replaceCollection”(现在发生的情况)、“replaceDocuments” ”、“插入文档”(你想要的)。
重新阅读您的代码后,为什么要使用聚合管道和$out
来复制一个文档?这就是用大炮打麻雀。
您可以通过应用程序更可靠地完成此操作。阅读文档,然后将其保存到其他集合中。
关于java - 将文档从一个集合移动到另一个集合会覆盖该文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782168/