Search code examples
c#mongodblinqnosqlmongodb-.net-driver

How to 'Find And Push' element in an array inside of another array in a document using LINQ to MongoDb


I want to push an element to an array inside another array inside a document using LINQ with latest MongoDb driver

here is the code:

public class Contract : BaseDocument
{
    public ObjectId Id {get;set;}
    ...
    public List<Payment> Payments {get;set;}
}

public class Payment : BaseDocument
{
    public ObjectId Id {get;set;}
    public double TotalPaymentAmount {get;set;}
    public DateTime PaymentWorthDate {get;set;}
    ...
    public List<PaymentTransaction> PaymentTransactions {get;set;}
}

public class PaymentTransaction 
{
    public double AmountPaid {get;set;}
    public DateTime TransactionDateTime {get;set;}
}

So how to push new PaymentTransaction to a specific Payment in a particular Contract using 'LINQ Expression' ?

Thanks!


Solution

  • LINQ stands for Language-Intergrated Query while you're trying to update the document so actually you need UpdateOne method. Since you have more than one nested array you can leverage regular query to identify Contract along with the $ positional operator to indicate which Payment (nested object) should be modified.

    .NET MongoDB driver offers a special syntax where you can pass -1 as an index to indicate that this item will be identified based on filtering condition. Try:

    var filterBuilder = Builders<Contract>.Filter;
    var filter = filterBuilder.Eq(x => x.Id, contractId) &
                    filterBuilder.ElemMatch(doc => doc.Payments, el => el.Id == paymentId);
    
    var updateBuilder = Builders<Contract>.Update;
    var update = updateBuilder.Push(doc => doc.Payments[-1].PaymentTransactions, new PaymentTransaction());
    
    col.UpdateOne(filter, update);