MongoDB驱动程序查询*过滤器定义构建器* Nin $ nin不在过滤器

时间:2016-10-17 12:40:08

标签: c# mongodb mongodb-query

有没有人使用C#.Net MongoDB驱动程序FilterDefinitionBuilder不在过滤器中?这是一个简单的例子,我把它放在一起,似乎无法开始工作。假设我们必须按原样保留集合。目标是只检索不在指定的ArtistGenresDocument列表中的ArtistDetailsDocument。

代码不会编译并声明“无法将lambda表达式转换为'MongoDB.Driver.FieldDefinition ArtistDetailsDocument,ArtistGenresDocument',因为它不是委托类型”。

感谢您的帮助! \ m / \ m /

public class ArtistDetailsDocument
{
    public ObjectId Id { get; set; }
    public String artist_ID { get; set; }
    public String artistName { get; set; }
}

public class ArtistGenresDocument
{
    public ObjectId Id { get; set; }
    public String artist_ID { get; set; }
    public String genre { get; set; }
}

IEnumerable<ArtistGenresDocument> list = await ArtistGenresCollection.Find(x => x.genre == "Pop" | x.genre == "Easy Listening").ToListAsync();

var filter = Builders<ArtistDetailsDocument>.Filter.Nin<ArtistGenresDocument>(x => x.artist_ID, list);

var ArtistDetailsDocuments = ArtistDetailsCollection.Find(filter);

2 个答案:

答案 0 :(得分:3)

以下是pieperu帮助下的解决方案!

IEnumerable<ArtistGenresDocument> list = await ArtistGenresCollection
    .Find(x => x.genre == "Pop" || x.genre == "Easy Listening")
    .ToListAsync();

var filter = Builders<ArtistDetailsDocument>
    .Filter
    .Nin(x => x.artist_ID, list.Select(l => l.artist_ID));

var ArtistDetailsDocuments = await ArtistDetailsCollection
    .Find(filter)
    .ToListAsync();

public class ArtistDetailsDocument
{
    public ObjectId Id { get; set; }
    public String artist_ID { get; set; }
    public String artistName { get; set; }
}

public class ArtistGenresDocument
{
    public ObjectId Id { get; set; }
    public String artist_ID { get; set; }
    public String genre { get; set; }
}

答案 1 :(得分:1)

您需要从第一个查询返回的对象集合中提取Artist_Id,您当前正在将整个对象集合与第二个查询中的Artist_ID字段进行比较

您可以在查找后使用查询中的Project()方法实现此目的:

.Project(x => x.artist_ID).ToListAsync()

或在返回结果后使用linq

list.Select(l => l.artist_ID)

注意:我认为此处的字段为artist_ID,因此您可能需要将artist_ID更改为ArtistGenresDocument模型中的字段

尝试这样的事情(我还纠正了代码中的一些其他错误)

IEnumerable<ArtistGenresDocument> list = await ArtistGenresCollection
    .Find(x => x.genre == "Pop" || x.genre == "Easy Listening")
    //This is where your projection would go if you didnt use linq
    //.Project(x => x.artist_ID).ToListAsync()
    .ToListAsync();

var filter = Builders<ArtistDetailsDocument>
    .Filter
    //This is where we are plucking the Artist id with linq
    .Nin<ArtistGenresDocument>(x => x.artist_ID, list.Select(l => l.artist_ID));

var ArtistDetailsDocuments = await ArtistDetailsCollection
    .Find(filter)
    .ToListAsync();

我希望这会有所帮助