0

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

1 Answer 1

1

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