Spring数据/MongoDB:一次性将单个文档从一个集合复制到另一个集合

Spring Data / MongoDB: Copy a single document from one collection to another in one go

如何使用 Spring 数据将单个文档从一个集合复制到另一个 in one go

现在,我正在通过 id 查找文档并将其保存到另一个集合中。但那是 2 个步骤。

是否有类似 findAndCopy 的功能?

您可以使用聚合框架来完成,如下所示。

MatchOperation matchOperation = match(Criteria.where("somekey").is("someValue"));

ProjectionOperation projectionOperation = project().andExpression("someKey").as("Key")
        .andExpression("otherKey").as("SomeOtherKey");

OutOperation outOperation = out("New_Collection_Name");
Aggregation aggregation = newAggregation(matchOperation, projectionOperation, outOperation);

mongoTemplate.aggregate(aggregation, "Existing_Collection_Name", ResultClass.class);

此处应根据您在投影中使用的字段来定义ResultClass。

如果你想将所有的字段写入新的集合(而不是只有几个),那么你可以在上面的管道中删除投影操作。在这种情况下,ResultClass 将与您的文档(输入)相同 class