« Mongodb and csharp » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Aucun résumé des modifications
Ligne 17 : Ligne 17 :
var result = (await collection.FindAsync(filter)).ToList();
var result = (await collection.FindAsync(filter)).ToList();
</kode>
</kode>
= [https://stackoverflow.com/questions/30333925/how-do-i-log-my-queries-in-mongodb-c-sharp-driver-2-0 Log] =
<kode lang='cs'>
var mongoUrl = new MongoUrl("MONGODB_CONNECTION_STRING");
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
mongoClientSettings.ClusterConfigurator = cb =>
{
    cb.Subscribe<CommandStartedEvent>(e =>
    {
        logger.LogTrace($"{e.CommandName} - {e.Command.ToJson()}");
    });
};
this.mongoClient = new MongoClient(mongoClientSettings);
</kode>
Configure the [[Asp.net_core_7#Log|Log]] so it will be displayed in Visual Studio Output Debug window.

Version du 20 mars 2024 à 10:22

Access to a collection

Cs.svg
var mongoClient = new MongoClient("MONGODB_CONNECTION_STRING");
var database = mongoClient.GetDatabase("DB_NAME");
var collection = database.GetCollection<Collection>("COLLECTION_NAME");

Filter

Cs.svg
var builder = Builders<MyClass>.Filter;
FilterDefinition<MyClass> filter = filterDefinition.Empty;

filter &= builder.Eq(x => x.Property1, "id");
filter &= builder.In(x => x.Property1, new[] { "id1", "id2" });  // filter by Property1 equals to one of the ids

var result = (await collection.FindAsync(filter)).ToList();

Log

Cs.svg
var mongoUrl = new MongoUrl("MONGODB_CONNECTION_STRING");
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
mongoClientSettings.ClusterConfigurator = cb =>
{
    cb.Subscribe<CommandStartedEvent>(e =>
    {
        logger.LogTrace($"{e.CommandName} - {e.Command.ToJson()}");
    });
};
this.mongoClient = new MongoClient(mongoClientSettings);

Configure the Log so it will be displayed in Visual Studio Output Debug window.