在Mongo Linq查询中执行相交的机制是什么 [英] what is the mechanism for performing an intersect in a Mongo Linq query

查看:69
本文介绍了在Mongo Linq查询中执行相交的机制是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

So assuming that the Mongo Linq provider does not support this - How do I go about it?

推荐答案

在MongoDB语法中,有一个

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.

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

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

在MongoDB C#驱动程序中,您可以使用AnyIn将该操作符应用于两个数组.试试:

In MongoDB C# driver you can use AnyIn to apply that operator for two arrays. Try:

db.col.save({ Collection: [1,2,3] })l

然后用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();

这篇关于在Mongo Linq查询中执行相交的机制是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆