猫鼬批量更新操作

Mongoose bulk update operation

有没有办法在 mongoose 中对集合进行批量更新?我发现的策略使用原始收集驱动程序如下:

var bulk = Person.collection.initializeOrderedBulkOp();
bulk.find(query).update(update);
...
bulk.execute(callback)

但是,当我这样做时,bulk 是未定义的。是猫鼬不支持吗?

NOTE: Modern Mongoose releases support .bulkWrite() directly on the Model methods. It is preferable to use this method even in direct implementations of the MongoDB API, since it actually "safely downgrades" to use "individual calls" for the methods supplied in the batch in cases where connecting to a MongoDB version that does not support the "Bulk API" itself.

It still calls the same underlying "bulk methods" as described, but rather the software makes the decision how to correctly send to the server than your own code needing to make this determination.

Also note: That Ongoing mongoose releases now require you to .connect() in a way that means the connection must be resolved before other actions continue. Using new connection mechanisms ensures that accessors such as .collection described below are always present when you call them.


你可以这样做,但问题是当从基本驱动程序访问底层集合对象时,没有采取与已实现的猫鼬模型方法相同的预防措施。

所有模型方法都将底层方法与其他功能包装在一起,但最常见的方法是在尝试访问该方法之前确保数据库连接已打开。这确保了 Db 实例存在并且可以获得 Collection() 对象

一旦您在模型上使用了 .collection 访问器,那么您就可以自己完成所有操作了:

mongoose.connection.on('open',function(err,conn) {

   // now it's safe to use

   // { .. } Other code
   var bulk = Person.collection.initializeOrderedBulkOp();
   bulk.find(query).update(update);
   bulk.execute(callback)

});

或者其他一些基本确保连接确实已经建立的方法。

至于在不深入底层驱动程序级别的情况下对 Bulk API 方法的本机支持,是的,目前正在编写中。但是您仍然可以自己实现它,只要您连接到 MongoDB 2.6 服务器实例或更高版本,它就不会破坏代码。

关于查询和更新查询的更多详细信息。

var bulk = Person.collection.initializeOrderedBulkOp();
bulk.find(query).update(update);
bulk.execute(function (error) {
   callback();                   
});

查询正在使用数组搜索。
更新需要 $set:

var bulk = Person.collection.initializeOrderedBulkOp();
bulk.find({ '_id': { $in: [] } }).update({ $set: { status: 'active' } });
bulk.execute(function (error) {
     callback();                   
});

查询是搜索id

var bulk = Person.collection.initializeOrderedBulkOp();
bulk.find({ '_id': id }).update({ $set: { status: 'inactive' } });
bulk.execute(function (error) {
     callback();                   
});
Person.collection.update(
  { '_id': id }, 
  { $set: { status: 'inactive' } },
  { multi: true },
  callback
)

in {'_id': id} id是你要更新的record的id数组,其实就是where子句,你可以自己设置。在 {$set: {status: 'inactive'}} status 是你要更新的字段,你可以将自己的字段指定为 key:value 对。 {multi: true} 指定此操作将更新多条记录。 callback 有更新成功后调用的方法。