Reputation: 1646
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
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
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.
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
Reputation: 19
There's no built-in command for that. Fetch this document and count the keys yourself.
Upvotes: 0