MongoDB Driver Query * Filter Definition Builder * Nin $nin

本文关键字:Nin nin Builder Filter Driver Query MongoDB Definition | 更新日期: 2023-09-27 18:13:19

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

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

感谢你的帮助!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);

MongoDB Driver Query * Filter Definition Builder * Nin $nin

下面是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; }
}

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

您可以在find之后的查询上使用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();

希望对大家有所帮助