问题描述
我正在尝试使用以下代码对现有的 Mongo DB 集合执行多次插入
db.dados_meteo.aggregate([{ $match : { "POM" : "AguiardaBeira" } },{ $项目:{_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,湿":1,HMD":1,TMP":1 } },{ $out : "dados_meteo_reloaded" }])
但是每次我更改 $match 参数并进行新的聚合时,Mongo DB 都会删除以前的文档并插入新的结果.
你能帮帮我吗?
简短的回答是你不能":
如果 $out 操作指定的集合已经存在,那么在聚合完成后,$out 阶段会自动将现有集合替换为新的结果集合.$out 操作不会更改先前集合中存在的任何索引.如果聚合失败,$out 操作不会更改预先存在的集合.
作为一种解决方法,您可以在聚合之后将由 $out
指定的集合文档复制到永久"集合中,方法有以下几种(但其中一种都不是理想的):
- copyTo() 是最简单的,请注意警告.不要为了小的结果而使用其他.
- 使用JS:
db.out.find().forEach(function(doc) {db.target.insert(doc)})
- 使用 mongoexport/mongoimport
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" }
] )
But each time I change the $match parameters and make a new aggregation, Mongo DB deletes the previous documents and inserts the new result.
Could you help me?
The short answer is "you can't":
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() 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 聚合结果附加到现有集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!