我有item
课程:
class item
{
[BsonId]
public ObjectId _id { get; set; }
public int code { get; set; }
public string Name { get; set; }
public int salePrice { get; set; }
public int itemCount{ get; set; }
}
我希望使用itemCount
code
我可以通过两步完成:
首先:使用itemCount
作为过滤器找到code
:
var filter = Builders<item>.Filter.Eq("code", listitems.code);
var itemsCollection = _database.GetCollection<item>("item");
var itemsList = itemsCollection.Find(filter).ToList<item>();
第二次:增加itemCount
,然后更新文档:
int itemsCounter = 0;
if (itemsList.Count()>0)
itemsCounter = itemsList.ElementAt(0).itemCount;
itemsCounter++ ;
filter = Builders<item>.Filter.Eq("code", listitems.code);
itemsCollection = _database.GetCollection<item>("item");
var update = Builders<item>.Update.Set("itemCount", itemsCounter);
var result = itemsCollection.UpdateOne(filter, update);
我的问题:我可以一步完成吗?
答案 0 :(得分:1)
这一步的答案是:
var filter = Builders<BsonDocument>.Filter.Eq("code", listitems.code);
var update = new BsonDocument("$inc", new BsonDocument { { "itemCount", 1 } });
var coll = _database.GetCollection<BsonDocument>("item");
var doc = coll.FindOneAndUpdateAsync(filter, update).Result;