java - 将文档从一个集合移动到另一个集合会覆盖该文档

标签 java mongodb aggregation-framework spring-data-mongodb

通过与 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/

相关文章:

java - GWT 中的 ClientBundles 和代码拆分?

node.js - Mocha 在与 Mongoose 连接时执行后挂起

mongodb - 根据关键值对文档进行排序和排名?

mongodb - Mongo 计算一组文档中每个值的出现次数

arrays - 在MongoDB中将多个文档转换为一个文档

mongodb - 我如何在 Mongo 上每天和每小时对数据进行分组?

java - Websocket 连接上出现“Access-Control-Allow-Origin”错误

java - 使用 Hibernate 注释注释 EnumMap<K, V>

java - 我如何从 Nanohttpd 提供外部 css、jpg 和 gif 文件(Nanohttpd 在普通电脑上运行,而不是在 Android 上运行)?

java - 如何使用 java 仅获取 mongodb 中文档的 objectId