mongodb - mongo聚合查询使用$out输出,执行的是替换操作而不是append操作

 悲剧制造商_469 发布于 2022-10-25 03:14

mongo聚合查询遇到的一个问题

当前对mongo数据库的一张表做一些聚合查询的操作,考虑到数据量太大,从数据库查寻出来结果还是需要插入到数据库,故决定,将查询结果插入到一个临时的集合中,使用mongo的$out操作。根据业务需求,需要执行三次这样的聚合查询,测试发现$out输出到新的集合是,执行替换操作,而不是append操作,以下是官网解释:

  • The $out operation creates a new collection in the current database if one does not already exist.

  • 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. The $out operation does not change any indexes that existed on the previous collection.

现在我依然有这样的需求,将多次聚合的结果放在一张表中,该怎么做?

1 个回答
  • 从2.6开始aggregation的返回值是一个游标。既然是游标,就不要求你在客户端把整个结果集缓存到内存中再操作,很直接的想法就是遍历这个游标,一条一条插进目标集合就可以了。比如在shell中:

    db.coll.aggregate([...]).forEach(function(doc) {
      db.target_coll.save(doc);
    });
    2022-10-26 14:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有