I'm using auto increment fild as discussed here.
I can execute this example in Mongo Console, but how can I implement such a thing using c# driver ?
db.products.insert({
"_id":getNextSequenceValue("productid"),
"product_name":"Apple iPhone",
"category":"mobiles"
})
Is it possible to specify a function in the write operation ?
I could call this function using Eval, but as it is being deprecated, I would like to find a solution without using it.
How Does Auto-increment Work in MongoDB? Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.
The $inc operator increments a field by a specified value and has the following form: { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
As exemplified here:
var client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("myDatabase");
var counterCol = db.GetCollection("counters")
var result = counterCol.FindAndModify(new FindAndModifyArgs()
{
Query = Query.EQ(d => d.Id, "orderId"),
Update = Update.Inc(d => d.Value, 1),
VersionReturned = FindAndModifyDocumentVersion.Modified,
Upsert = true, //Create if the document does not exists
});
Using the new v2.x Driver :
public class Sequence
{
[BsonId]
public ObjectId _Id { get; set; }
public string Name { get; set; }
public long Value { get; set; }
public void Insert(IMongoDatabase database)
{
var collection = database.GetCollection<Sequence>("sequence");
collection.InsertOne(this);
}
internal static long GetNextSequenceValue(string sequenceName, IMongoDatabase database)
{
var collection = database.GetCollection<Sequence>("sequence");
var filter = Builders<Sequence>.Filter.Eq(a => a.Name, sequenceName);
var update = Builders<Sequence>.Update.Inc(a => a.Value, 1);
var sequence = collection.FindOneAndUpdate(filter, update);
return sequence.Value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With