1

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!

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.