Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Auto Increment field in Mongo C# Driver without using eval?

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.

like image 989
André Pontes Avatar asked May 17 '18 15:05

André Pontes


People also ask

How do I auto increment a field in MongoDB?

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.

How do I increment a field in MongoDB?

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.


1 Answers

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;
    }
}
like image 76
André Pontes Avatar answered Sep 24 '22 15:09

André Pontes