1

I have a mongodb collections (docs), for every document (doc1) , I want to find all other documents (doc2) where the intersection of doc2.LinexText[any].Words with doc1.IDs is not empty.

doc {
    "IDs": ["ID1", "ID2"],
    "LineText": [{
        "Words": ["W1", "W2"]
    }]
}

public class MongoDocument : Entity
{       
        public List<string> IDs{ get; set; } = new List<string>();
        public List<LineText> Lines { get; set; } = new List<LineText>();

}

public class LineText
{          
      public List<string> Words { get; set; } = new List<string>();
}

my first attempt was to use below filter but it didn't work (Unsupported filter exception)

var filter = Builders<MongoDocument>.Filter.And(Builders<MongoDocument>.Filter.ElemMatch(x => x.LinesText, x => x.Words.Intersect(mongoDoc.IDs).Any());

I got this exception :

System.ArgumentException: 'Unsupported filter: Any({document}{Words}.Intersect(value(System.Collections.Generic.List`1[System.String]))).'

so for now , I am only matching the first ID until I figure out how to match any ID in the list.

var filter = Builders<MongoDocument>.Filter.And(Builders<MongoDocument>.Filter.ElemMatch(x => x.LinesText, x => x.Words.Contains(mongoDoc.IDs[0]));

how can I perform this intersection using MongoDB .NET Driver ?

1 Answer 1

1

You can do this by building an AnyIn filter to represent the intersect like this

   var intersectFilter = Builders<LineText>.Filter.AnyIn(x => x.Words, mongoDoc.IDs);
   var combinedFilter = Builders<MongoDocument>.Filter.ElemMatch(x => x.Lines, intersectFilter);
   var items = collection.Find(combinedFilter).ToList();

This will check if there is any Word that contains the same element as mongoDoc.

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.