如何将Mongo DB聚合结果附加到现有集合? [英] How do I append Mongo DB aggregation results to an existing collection?

查看:73
本文介绍了如何将Mongo DB聚合结果附加到现有集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在现有的Mongo DB集合上执行几次插入

I am trying to perform several insertions on an existent Mongo DB collection using the following code

db.dados_meteo.aggregate( [
                  { $match : { "POM" : "AguiardaBeira" } },
                  { $project : {
                     _id : { $concat: [
                        "0001:",
                      { $substr: [ "$DTM", 0, 4 ] },
                      { $substr: [ "$DTM", 5, 2 ] },
                      { $substr: [ "$DTM", 8, 2 ] },
                      { $substr: [ "$DTM", 11, 2 ] },
                      { $substr: [ "$DTM", 14, 2 ] },
                      { $substr: [ "$DTM", 17, 2 ] }
                       ] },
                    "RNF" : 1, "WET":1,"HMD":1,"TMP":1 } },
                  { $out : "dados_meteo_reloaded" }
              ] )

但是每次我更改$ match参数并进行新的聚合时,Mongo DB都会删除以前的文档并插入新的结果.

But each time I change the $match parameters and make a new aggregation, Mongo DB deletes the previous documents and inserts the new result.

你能帮我吗?

推荐答案

简短的回答是你不能":

The short answer is "you can't":

如果$ out操作指定的集合已经存在,那么在聚合完成后,$ out阶段会用新的结果集合原子替换现有的集合. $ out操作不会更改上一个集合中存在的任何索引.如果聚合失败,则$ 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. The $out operation does not change any indexes that existed on the previous collection. If the aggregation fails, the $out operation makes no changes to the pre-existing collection.

作为一种解决方法,您可以在聚合之后将$out指定的收集文档复制到永久"收集中,可以采用以下几种方法之一(虽然这都不是理想的方法):

As a workaround, you can copy the collection document specified by $out to a "permanent" collection just after aggregation, in one of a several ways (non of which is ideal though):

  • copyTo()最简单,请注意警告.请勿将其他用于小的结果.
  • 使用JS:db.out.find().forEach(function(doc) {db.target.insert(doc)})
  • 使用mongoexport/mongoimport
  • copyTo() is the easiest, mind the Warning. Don't use other for small results.
  • Use JS: db.out.find().forEach(function(doc) {db.target.insert(doc)})
  • Use mongoexport / mongoimport

这篇关于如何将Mongo DB聚合结果附加到现有集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆