2

MongoDB 支持使用聚合管道进行更新(https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/)。这是示例查询(https://mongoplayground.net/p/i7A4YoIhyS5)。更新函数将数组(管道)作为第二个参数。

然而,在 Mongoose 中,事实证明您只能传递一个对象(通过文档https://mongoosejs.com/docs/api.html#model_Model.updateMany,我也尝试过自己并且不支持数组)。有什么方法可以在 Mongoose 中将更新与聚合管道一起使用?

4

1 回答 1

1

Mongoose 还没有为此实现方便的包装器。

但是,Model.collection提供了从本机驱动程序对基础集合对象的只读访问,包括其方法。

而不是Model.updateMany(),尝试使用Model.collection.updateMany(),它应该使用为 MongoDB Node.JS 驱动程序描述的语法

编辑

使用 Mongoose 5.12 和 MongoDB 4.2 的丑陋演示代码:

const mongoose=require('mongoose');

const testSchema = new mongoose.Schema({ test:String });

const testModel = mongoose.model('testModel',testSchema);

mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});

async function main() {
    const doc = new testModel({test:"testString"});
    await doc.save();
    const result = await testModel.collection.updateMany({},[{$set:{updated:{$concat:["$test",{$toString:"$_id"}]}}}]);
    console.log("matchedCount:",result.matchedCount);
    console.log("modifiedCount:",result.modifiedCount);
    const newdoc = await testModel.findOne({});
    console.log(newdoc);
    process.exit();
}

main();

上述输出:

matchedCount: 1
modifiedCount: 1
{
  _id: 606945d4d5a5d9bec9038a59,
  test: 'testString',
  __v: 0,
  updated: 'testString606945d4d5a5d9bec9038a59'
}
于 2021-04-02T17:00:28.893 回答