问题
How do I write a where clause in Linq for Mongo to determine if any member of a local collection is contained by a collection in my document.
i.e. (this was what I was expecting to work, but didn't)
var myLocalList = <PopulateMyLocalList>;
var myDocs = db.GetCollection<MyDoc>("MyDocs").AsQueryable();
var result = myDocs.Where(d => d.MyCollection.Intersect(myLocalList).Any());
So assuming that the Mongo Linq provider does not support this - How do I go about it?
回答1:
In MongoDB syntax there's a $in operator which works exactly like intersect+any when you want to match an in-memory array with another array embedded in your document.
If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. , , etc.)
In MongoDB C# driver you can use AnyIn to apply that operator for two arrays. Try:
db.col.save({ Collection: [1,2,3] })l
Then in C#:
var filterBuilder = Builders<YourModel>.Filter;
var inMemoryList = new List<int>() { 3, 4, 5 };
var result = Col.Find(filterBuilder.AnyIn(x => x.Collection, inMemoryList)).ToList();
来源:https://stackoverflow.com/questions/51959853/what-is-the-mechanism-for-performing-an-intersect-in-a-mongo-linq-query