Official Docs Site
Docs zh-cn
Simple Use
生成Mongo自增主键
public long GetSequence(string collectionName = "")
{
MongoClient Client=new MongoClient(dbconn);
if (string.IsNullOrEmpty(collectionName))
{
collectionName = typeof(T).Name;
}
var filter = Builders<Sequence>.Filter.Where(p => p.CollectionName == collectionName);
var update = Builders<Sequence>.Update.Inc(x => x.Value, 1);
var options = new FindOneAndUpdateOptions<Sequence, Sequence>() { ReturnDocument = ReturnDocument.After, IsUpsert = true };
var seq = Client.GetDatabase(dbName).GetCollection<Sequence>("Sequence").FindOneAndUpdate(filter, update, options);
return seq.Value;
}
public class Sequence
{
public ObjectId Id { get; set; }
public string CollectionName { get; set; }
public long Value { get; set; }
}
RunCommand with JsonCommand
public TResult RunCommand<TResult>(string json)
{
new MongoClient(connectstring)
.GetDatabase(dbname)
.GetCollection<TDocument>()
.RunCommand(new JsonCommand<TResult>(json));
}