Search code examples
c#mongodbmongodb-querymongodb-.net-driver

How to insert complex array object if not exists using MongoDB C# Driver


I am trying to insert an object to an array property of my document only if the array doesn't contain another object with the same key. However I could not find the correct filter that does this using the C# driver. Details are below. Can you help me build the filter?

Here are my models

public class Document : Entity
{
    public string Id { get; set; }
    public string Name { get; set; }
    public List<DocumentSubject> Subjects { get; set; }
    ...
}


public class DocumentSubject
{
    public string Id { get; set; }
    public DocumentSubjectType Type { get; set; }
    public bool CanOpenIssue { get; set; }
    ...
}

Here is what I did so far (of course it's not complete)

var filter = Filter.And(
              Filter.Eq(x => x.Id, id),
              "PUT SOME FILTER FOR ARRAY ITEM EXISTENCE CHECK BY ID"
            );


var updater = Updater.AddToSet(x => x.Subjects, subject);

var u =Collection.UpdateOne(filter, updater);

Solution

  • You can try below query.

    The below query will use $elemMatch to check DocumentSubject array for element with id.

    var queryBuilder = Builders<Document>.Filter;
    var elemMatchBuilder = Builders<DocumentSubject>.Filter;
    var filter = queryBuilder.Eq(document => document.Id, id) & queryBuilder.ElemMatch(document => document.Subjects, elemMatchBuilder.Ne(document => document.Id, subjectId));
    
    var updater = Updater.Push(x => x.Subjects, subject);
    
    var u = collection.UpdateOne(filter, updater);