有没有办法用一个查询插入或更新/替换MongoDB中的多个文档?

假设以下集合:

[
    {_id: 1, text: "something"},
    {_id: 4, text: "baz"}
]

现在我想添加多个文档,其中一些文档可能已经在集合中.如果这些文件已经在收集中,我想更新/替换它们.例如,我想插入以下文件:

[
    {_id:1, text: "something else"},
    {_id:2, text: "foo"},
    {_id:3, text: "bar"}
]

查询应插入带有_id 2和3的文档.还应使用_id 1更新/替换文档.完成此过程后,集合应如下所示:

[
    {_id:1, text: "something else"},
    {_id:2, text: "foo"},
    {_id:3, text: "bar"},
    {_id:4, text: "baz"}
]

一种方法可能是使用insertMany:

db.collection.insertMany(
   [ {...}, {...}, {...} ],
   {
      ordered: false,
   }
)

如果出现重复,该查询将发出一个writeErrors,其中包含一个对象数组,其中包含未能插入的文档的索引.我可以浏览并更新它们.

But that process is cumbersome. Is there a way to insert or update/replace many documents in one query?

推荐答案

正如here所说,要做你需要的事情,你可以把这样的东西放进go

playbook js

(* warning: untested code)

use YOUR_DB
var bulk = db.collection.initializeUnorderedBulkOp();
bulk.find( { _id : 1 } ).upsert().update( { $set: { "text": "something else" } } );
bulk.find( { _id : 4 } ).upsert().update( { $set: { "text": "baz" } } );
bulk.find( { _id : 99 } ).upsert().update( { $set: { "text": "mrga" } } );
bulk.execute();

并与

mongo < playbook js

我必须这样做,因为我试图更新/插入1000多个文档的任何方法都因限制而无效.

写入命令最多只能接受1000个操作.mongo shell中的Bulk()操作和驱动程序中的类似方法没有此限制.

source

Mongodb相关问答推荐

更新查询mongoose 中的礼宾更新字段

如何填充Mongoose中的嵌套引用

MongoDB 在一个聚合中包含多个组

MongoDB Aggregate 根据时间进行多重分组

如何在 go mongo-driver 中为 options.FindOne() 设置限制

在运算符 $map 中嵌入运算符 $exists

如何在 Mongoose 中定义一个通用的嵌套对象

解析命令行时出错:unrecognized option --rest

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

使用 EventSourcing(NodeJS、MongoDB、JSON)跨多个偶尔连接的客户端同步数据

Mongoid 有 Map/Reduce 吗?

在 Heroku 上使用 Node 读取、写入和存储 JSON

我怎样才能更快地scrape

MongoDB - 清除嵌套数组中的元素

如何在 Mongoose 中更新数组值

嵌套数组内的Mongodb增量值

Mongoose.js 通过一个 connect() 调用创建到 MongoDB 的多个连接

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

遍历所有 Mongo 数据库

停止副本集 MongoDB