在MongoDB中插入MAX(numberField)+ 1

时间:2016-11-08 06:27:01

标签: node.js mongodb mongoose insert max

插入新文档时我只想插入一个值必须为max(field) + 1.的字段 例如 像这样的东西

db.test.insert({numberField : MAX(numberField) + 1})

此外,如果没有文档,第一个文档的numberField值必须为0。在增量1,2,3之后,就像明智一样。

我不希望两个查询一个查找最大数字,另一个查询按1递增。

任何人都可以帮忙.Thanku

2 个答案:

答案 0 :(得分:1)

有很多关于如何在mongoose中创建自动增量字段的堆栈溢出帖子。

auto-increment-document-number-in-mongo-mongoose

create-unique-autoincrement-field-with-mongoose

@edtech

以下是使用Mongoose实现自动递增字段的一个很好的示例:

var CounterSchema = Schema({
    _id: {type: String, required: true},
    seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
    testvalue: {type: String}
});

entitySchema.pre('save', function(next) {
    var doc = this;
    counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter)   {
        if(error)
            return next(error);
        doc.testvalue = counter.seq;
        next();
    });
});

您应首先从mongodb documentation执行第1步。

编辑 - 没有猫鼬的解决方案 - Aka MongoDB本机驱动程序

你可以使用mongodb native node.js driver并实现这些堆栈溢出帖子中解释的解决方案之一:

auto-increment-in-node-mongodb-native-using-counters-collection

Creating incrementing numbers with mongoDB

答案 1 :(得分:0)

没有内置命令。获取此文档并自行计算密钥。