Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

Insert MAX(numberField) + 1 in MongoDB

While insert a new document i just want to insert a field whose value must be max(field) + 1. For eg Something like this

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

Also if there is no document,1st document must have value 0 for numberField.After that increment1,2,3 like wise.

I dont want two queries one to find max number and other to insert incrementing that by 1.

Can anyone please help.Thanku

Upvotes: 1

Views: 797

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23515

There is plenty of stack overflow posts about how to create an auto-increment field in mongoose.

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

create-unique-autoincrement-field-with-mongoose


@edtech

Here is a good example of auto-incremented fields implementation using 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();
    });
});

You should perform the Step 1 from mongodb documentation firstly.


EDIT - Soluce without mongoose - Aka MongoDB Native Driver

You can use the mongodb native node.js driver and implements one of the soluce explained in theses stack overflow posts:

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

Creating incrementing numbers with mongoDB

Upvotes: 1

Joynal
Joynal

Reputation: 19

There's no built-in command for that. Fetch this document and count the keys yourself.

Upvotes: 0

Related Questions