在 Mongo Linq 查询中执行相交的机制是什么

Tim*_*vis 4 c# linq mongodb

如何在 Linq for Mongo 中编写 where 子句来确定我的文档中的集合是否包含本地集合的任何成员。

即(这是我期望的工作,但没有)

var myLocalList = <PopulateMyLocalList>;

var myDocs = db.GetCollection<MyDoc>("MyDocs").AsQueryable();
var result =  myDocs.Where(d => d.MyCollection.Intersect(myLocalList).Any());
Run Code Online (Sandbox Code Playgroud)

因此,假设 Mongo Linq 提供程序不支持此功能 - 我该怎么办?

mic*_*ckl 8

在 MongoDB 语法中,有一个$in运算符,当您想要将内存中的数组与文档中嵌入的另一个数组进行匹配时,它的工作方式与 intersect+any 完全相同。

如果该字段包含一个数组,则 $in 运算符会选择其字段包含一个数组的文档,该数组至少包含一个与指定数组中的值匹配的元素(例如 、 等)

在 MongoDB C# 驱动程序中,您可以将该AnyIn运算符应用于两个数组。尝试:

db.col.save({ Collection: [1,2,3] })l
Run Code Online (Sandbox Code Playgroud)

然后在 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();
Run Code Online (Sandbox Code Playgroud)