简体   繁体   English

使用Lambda表达式查询ID列表的MongoDB

[英]Querying MongoDB with List of IDs using Lambda Expression

I'm hoping someone can help me: 我希望有人可以帮助我:

I'm using an interface to access my data, the Find method is: 我正在使用接口访问数据,Find方法是:

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

I'm trying to build an expression to fetch all ObjectIds within a list of ObjectIds. 我正在尝试构建一个表达式来获取ObjectId列表中的所有ObjectId。

something like: r => r.id.ContainsAny(List_Of_IDs); 类似于:r => r.id.ContainsAny(List_Of_IDs); //where List_Of_IDs is of type: List //其中List_Of_IDs的类型为:List

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

But I get an error that ContainsAny doesn't support this parameter. 但是,我收到一个包含ContainsAny不支持此参数的错误。

I was hoping to duplicate the functionality of an IN statement in SQL. 我希望在SQL中复制IN语句的功能。 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. 我的目标是我希望用户集合包含产品列表作为ObjectId列表,然后我要查询产品集合并获取用户的产品ID列表中的所有文档。

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. .ContainsAny()仅用于数组字段。 . So you could use it if your .id was an array type. 因此,如果您的.id是数组类型,则可以使用它。

For your case you're looking for .Contains() or .In() : 对于您的情况,您正在寻找.Contains().Contains() .In()

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

Which, coincidentally, is equivalent to: 巧合的是,它等于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM