what is the mechanism for performing an intersect in a Mongo Linq query

你离开我真会死。 提交于 2020-06-28 07:28:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!