简体   繁体   English

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

[英]How to use C# to insert document into existing embedded documents?

I have the structure below in C# (a customer with invoices).我在 C# 中有以下结构(有发票的客户)。 I'm struggling to insert into an existing mongodb record.我正在努力插入现有的 mongodb 记录。 I'm using C# .NET 4.5 together with MongoDB 2.4.我将 C# .NET 4.5 与 MongoDB 2.4 一起使用。 I would like to insert a new invoice into an existing customer record.我想在现有客户记录中插入新发票。

I receive the error "duplicate key error" which I understand but I don't know how to append to the Invoices object within the Customer object.我收到错误“重复键错误”,我理解但我不知道如何附加到客户对象中的发票对象。

Any help much appreciated.非常感谢任何帮助。

My attempt我的尝试

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

Error错误

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

Classes班级

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; }
}

Update更新

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);

Second update第二次更新

I've tried the following but it inserts a new invoice object (outside Invoices)我尝试了以下操作,但它插入了一个新的发票对象(在发票之外)

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

Third update第三次更新

This approach overwrites the customer's existing invoices and replaces it with this "hello" invoice.这种方法会覆盖客户现有的发票,并将其替换为这张“hello”发票。 How can you append to the existing invoices..?你怎么能附加到现有的发票..?

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

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

This works, notice the use of Push - otherwise it's the same as the set approach above (see third update)这有效,请注意 Push 的使用 - 否则与上面的 set 方法相同(请参阅第三次更新)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM