Mongodb 如何从原始数据库中的所有文档中减去特定的数字

Mongodb 如何从原始数据库中的所有文档中减去特定的数字,mongodb,Mongodb,作为我的标题,我想从我的所有文档中减去一个specificNumber,比如说200,其中someAttribute在mongoDB中的值大于specificNumber 这是我的模式 const mongoose = require('mongoose'); const Schema = mongoose.Schema; let Employee = new Schema({ first_name: { type: String }, last_name: { type: S

作为我的标题,我想从我的所有文档中减去一个
specificNumber
,比如说
200
,其中
someAttribute
在mongoDB中的值大于
specificNumber
这是我的模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Employee = new Schema({
    first_name: { type: String },
    last_name: { type: String },
    title: { type: String },
    email: { type: String },
    gender: { type: String },
    location: { type: String },
    phone: { type: String },
    branch: { type: String },
    department: { type: String },
    positionX: { type: Number },
    positionY: { type: Number }
},
    { collection: 'Employees' });
module.exports = mongoose.model('Employees', Employee)


我搜索了mongoDB论坛,他们使用了
aggregation
方法,但问题是,它只返回值,不修改数组。
我该怎么做?

您可以使用
Model.updateMany
。在查询中使用
$gt
,在更新中使用
$inc
。您可以在
$inc
运算符中使用负值

const updatedDocuments = await Employee.updateMany(
            { [someAttribute]: { $gt: someNumber } },
            { $inc: { [someAttribute]: -someNumber } }
        );

您可以使用
Model.updateMany
。在查询中使用
$gt
,在更新中使用
$inc
。您可以在
$inc
运算符中使用负值

const updatedDocuments = await Employee.updateMany(
            { [someAttribute]: { $gt: someNumber } },
            { $inc: { [someAttribute]: -someNumber } }
        );