C#Mongo db驱动程序更新现有文档

时间:2017-10-30 13:56:58

标签: mongodb-.net-driver

我在mongo db中有一个具有某些属性的现有文档。当我尝试使用具有相同ID但具有更多属性的文档更新此文档时,它不会更新它。我正在使用mongo db驱动程序版本2.4.4

以下是我的数据库中的现有文件

{
    "_id" : "1234",
    "AccountNumber" : "3453535345354",
    "Name" : "new1",
    "PhoneNumber" : "34534535353534543",
    "ETag" : "6ba32e6e-3808-41f5-9b28-0ea882d9c629",
    "Id" : "1234" 
}

现在,当我尝试使用以下文档更新/替换此文档时,它不起作用:

{
    "AccountNumber": "3453535345354",
    "Name":"new1",
    "PhoneNumber":"34534535353534543",
    "TempProperty":"something new",
    "ETag" : "6ba32e6e-3808-41f5-9b28-0ea882d9c629",
    "Id" : "1234",
    "_id" : "1234"
}

以下是我的upsert方法的C#代码:

 public async Task UpsertDocument(string collectionId, string documentId, BsonDocument item)
        {
            var collection = database.GetCollection<BsonDocument>(collectionId);

            var initialCorrelationId = item["ETag"].AsString;
            item["ETag"] = Guid.NewGuid().ToString();
            var builders = Builders<BsonDocument>.Filter;

            var filter = builders.Eq(x => x["Id"], documentId) & builders.Eq(x => x["ETag"], initialCorrelationId);

            var options = new FindOneAndReplaceOptions<BsonDocument, BsonDocument>
            {
                ReturnDocument = ReturnDocument.Before,
                IsUpsert = true
            };

            try
            {
                item["Id"] = documentId;
                item["_id"] = documentId;

                await collection.FindOneAndReplaceAsync(filter, item, options);
            }
            catch (MongoCommandException ex) when (ex.Code == 11000)
            {
                throw new ConcurrencyException(
                    $"Error upserting item with id {documentId} and etag {item["Etag"]}{Environment.NewLine}{item.ToJson()}");
            }
        }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

假设你有一个课程如下:

public class Thing
{
    public ObjectId Id { get; set; }
    public string AccountNumber { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
    public string ETag { get; set; }
    public string SecondId { get; set; }
}

以下代码可以满足您的需求:

var context = new Context();
var tempProperty = "newValue";
var id = "1234"; // This should be unique
var builder = Builders<Thing>.Filter;
var filter = builder.Eq(x => x.SecondId, id);
var update = Builders<Thing>.Update
    .Set("TempProperty", tempProperty);
context.ThingCollection.UpdateOne(filter, update, new UpdateOptions() {IsUpsert = true});

我刚刚将Id重命名为SecondId。