我正在使用自动增量fild,如here所述。
我可以在Mongo Console中执行此示例,但是如何使用c#驱动程序实现这样的功能呢?
db.products.insert({
"_id":getNextSequenceValue("productid"),
"product_name":"Apple iPhone",
"category":"mobiles"
})
是否可以在写操作中指定一个函数?
我可以使用Eval调用此函数,但由于它已被弃用,我希望找到一个不使用它的解决方案。
答案 0 :(得分:1)
例如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
});
使用新的v2.x驱动程序:
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;
}
}