将数据从一个集合复制到另一个集合 - MongoDB

问题描述 投票:0回答:1

我想使用 MongoDB 将数据从一个集合(集合 A)复制到另一个集合(集合 B)。我还想将现有数据保留在集合 A 中。 [我正在使用 MongoDB shell 版本 v4.4.3、带有 Node.js 和 Express 应用程序的 GoormIDE)

据我了解, $merge 运算符是最合适的,但是我一直遇到错误。我一直在使用下面的代码:

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate( [     { $match : {} },     { $merge : "<destinationnewcollection>" } ] )

这是产生的错误:

   uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "Failed to retrieve database or collection name from $merge. err=Error parsing $merge value.


     "code" : 8000,
        "codeName" : "AtlasError"
} : aggregate failed :

其他运算符(例如 add)似乎工作得很好,所以我对这个运算符失去了想法。对我做错了什么有什么想法吗?

mongodb
1个回答
3
投票

根据文档

{ $merge : "<destinationnewcollection>" }
应该可以工作。但是,看起来缩写形式不可用,所以使用

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate([
   { $unset: "_id" },
   { $merge: { into: "<destinationnewcollection>" } } 
])

db.getSiblingDB("<databasename>").<sourcecollection>.aggregate([
   { $unset: "_id" },
   { $merge: { into: { db: "<databasename>", coll: "<destinationnewcollection>" } } } 
])

您可以跳过

{ $match : {} }
- 它什么也不做。删除
_id
字段可确保在任何情况下都添加所有文档,还应该加快操作速度。

© www.soinside.com 2019 - 2024. All rights reserved.