如何使用C#将文档插入现有的嵌入式文档?

时间:2017-01-21 13:52:32

标签: c# mongodb

我在C#(有发票的客户)中有以下结构。我正在努力插入现有的mongodb记录。我正在使用C#.NET 4.5和MongoDB 2.4。我想在现有客户记录中插入新发票。

我收到错误“重复密钥错误”,我理解但我不知道如何附加到Customer对象中的Invoices对象。

任何帮助都非常感激。

我的尝试

var client = new MongoClient();
var database = client.GetDatabase("databasename");
var collection = database.GetCollection<Customer>("Customer");


var customerId = "..";
var builder = Builders<Customer>.Filter;
var filter = builder.Eq("Id", new ObjectId(customerId));
var matchedRecord = collection.Find(filter).SingleOrDefault();

// Insert new invoice into the customer record
matchedRecord.Invoices.Add(new Invoice {
  InvoiceNumber = "123456"
});

collection.InsertOne(matchedRecord);  // Error produced below

错误

E11000 duplicate key error collection: databasename.Customer index: _id_ dup key: { : ObjectId('..') }

public class Customer
{
    public ObjectId Id { get; set; }

    public string CustomerId { get; set; }

    public List<Invoice> Invoices { get; set; }
}

public class Invoice
{
    public string InvoiceNumber { get; set; }
}

更新

var builder = Builders<Customer>.Filter;
var filter = builder.Eq("Id", new ObjectId(customerId));

// Not sure how to use the FindOneAndUpdate method(?)
var matchedRecord = collection.FindOneAndUpdate<Customer>(filter);

第二次更新

我尝试了以下操作,但它会插入一个新的发票对象(在发票外)

var builder = Builders<Customer>.Filter;
var filter = builder.Eq("Id", new ObjectId(customerId));
var update = Builders<Customer>.Update.Set("Invoice.ClientName", "HELLO");

第三次更新

此方法会覆盖客户现有的发票,并将其替换为此“hello”发票。如何附加现有发票??

var update = Builders<Customer>.Update
            .Set("Invoices", new Invoice
            {
                ClientName = "HELLO"
            });

        var result = collection.UpdateOneAsync(filter, update);

1 个答案:

答案 0 :(得分:0)

这是有效的,请注意Push的使用 - 否则它与上面的设置方法相同(参见第三次更新)

var update = Builders<Customer>.Update.Push("Invoices", new Invoice
            {
                ClientName = "HELLO"
            });

var result = collection.UpdateOneAsync(filter, update);