使用Lambda表达式查询ID列表的MongoDB [英] Querying MongoDB with List of IDs using Lambda Expression

查看:729
本文介绍了使用Lambda表达式查询ID列表的MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能帮助我

我正在使用一个接口来访问我的数据,Find方法是:

I'm using an interface to access my data, the Find method is:

public IQueryable<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
    {
        return (IQueryable<T>) _db.GetCollection<T>(typeof(T).Name, WriteConcern.Acknowledged).AsQueryable().Where(expression);
    }

我正在尝试构建一个表达式以获取ObjectId列表中的所有ObjectId.

I'm trying to build an expression to fetch all ObjectIds within a list of ObjectIds.

类似: r => r.id.ContainsAny(List_Of_IDs); //其中List_Of_IDs的类型为:列表

something like: r => r.id.ContainsAny(List_Of_IDs); //where List_Of_IDs is of type: List

我也尝试过: r => r.id.ContainsAny(new [] {id1,id2,id3})//其中id1,id2,id3是ObjectId类型

I also tried: r => r.id.ContainsAny(new[] {id1, id2, id3}) //where id1, id2, id3 are type ObjectId

但是我收到一个包含ContainsAny不支持此参数的错误.

But I get an error that ContainsAny doesn't support this parameter.

我希望在SQL中复制IN语句的功能.我的目标是希望用户集合包含产品列表作为ObjectId列表,然后我要查询产品集合并在用户的产品ID列表中获取所有文档.

I was hoping to duplicate the functionality of an IN statement in SQL. My goal is that I want the user collection to contain a list of products as a list of ObjectIds and then I want to query the products collection and get all documents in the user's list of Product IDs.

这可能吗?有人知道我在做什么错吗?

Is this possible? Does anyone know what I'm doing wrong?

非常感谢您的协助! 史蒂夫

Thanks so much for any assistance! Steve

顺便说一句:这是我将表达式发送到存储库方法的地方:

BTW: here is where I send the expression to the repository method:

public static List<product> getByIDlist(List<ObjectId> IDs)
    {
        return (List<product>)repo.Find<product>(r => r.id.ContainsAny(IDs));       
    }

推荐答案

.ContainsAny() is only meant to be used on an array field.. So you could use it if your .id was an array type.

对于您的情况,您正在寻找.Contains().In():

For your case you're looking for .Contains() or .In():

public static List<product> getByIDlist(List<ObjectId> IDs)
{
    return (List<product>) repo.Find<product>(r => IDs.Contains(r.id);       
}

巧合的是,它等同于:

public static List<product> getByIDlist(List<ObjectId> IDs)
{
    return (List<product>) repo.Find<product>(r => r.id.In(IDs));       
}

这篇关于使用Lambda表达式查询ID列表的MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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