varbuilder = Builders<MyClass>.Filter;
FilterDefinition<MyClass> filter = builder.Empty;
filter &= builder.Exists(x => x.Property1);
filter &= builder.Eq(x => x.Property1, "value");
filter &= builder.In(x => x.Property1, new[] { "value1", "value2" }); // filter by Property1 equals to one of the values
filter &= builder.AnyIn(x => x.Tags, new[] { "value1", "value2" }); // filter by string[] Tags property which contains at least value1 or value2
filter &= builder.All(x => x.Tags, new[] { "value1", "value2" }); // filter by string[] Tags property which contains at least value1 and value2, order doesn't mattervarresult = await collection
.Find(filter)
.SortByDescending(x => x.Property1)
.Skip(100)
.Limit(10)
.ToListAsync();
varresult = (await collection.FindAsync(filter)).ToList();
Handle different types
// get all the documentsvarbsonDocumentCollection = database.GetCollection<BsonDocument>("MyCollection");
varfilter = Builders<BsonDocument>.Filter.Empty;
varresult = await bsonDocumentCollection.Find(filter).ToListAsync();
// get all the Class1 documentvarclass1Collection = database.GetCollection<Class1>("MyCollection");
await type1Collection.InsertOneAsync(newClass1 { Name = "Name1" });
varfilter = Builders<Class1>.Filter.Eq(x => x.Type, nameof(Class1));
varfilter = Builders<SimpleClass>.Filter.Exists(x => x.Name); // get all the documents which have a property Namevarresult = await class1Collection.Find(filter).ToListAsync();
classClass1
{
publicObjectId Id { get; set; }
publicstring Name { get; set; } = string.Empty;
publicstring Type { get; set; } = nameof(Class1);
}
Error: An error occurred while serializing the Values property of class ...: When using DictionaryRepresentation.Document key values must serialize as strings
classMyClass
{
publicObjectId Id { get; set; }
publicDictionary<MyEnum, int> Values { get; set; } = [];
}
// serialize the enum as string
BsonSerializer.RegisterSerializer(newEnumSerializer<MyEnum>(BsonType.String));