MongoDB Driver Query * Filter Definition Builder * Nin $nin Not in filter

c#, mongodb, mongodb-query

Solution

Here is the solution with help from 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; }
}

Problem

Has anyone used the C# .Net MongoDB Driver FilterDefinitionBuilder's not in filter? This is a simple example that I put together that I cannot seem to get to work. Assume that we must keep the collections as is. The goal is to retrieve only ArtistDetailsDocument's that are not in the specified ArtistGenresDocument list. The code will not compile and states "Cannot convert lambda expression to type 'MongoDB.Driver.FieldDefinition ArtistDetailsDocument,ArtistGenresDocument' because it is not a delegate type". Appreciate the help! \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); ```

Original source