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 中使用带有聚合管道的更新?
答案 0 :(得分: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'
}