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

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 30 : Ligne 30 :
var results = (await myCollection.AggregateAsync(pipeline)).List();
var results = (await myCollection.AggregateAsync(pipeline)).List();


BsonDocument GetMatchStage(GetTimeSeriesQuery getTimeSeriesQuery)
BsonDocument MatchStage(GetTimeSeriesQuery getTimeSeriesQuery)
{
{
     var match = new BsonDocument("property1", "value1");
     var match = new BsonDocument("property1", "value1");
Ligne 41 : Ligne 41 :
}
}


BsonDocument GetProjectionStage() =>
BsonDocument ProjectionStage() =>
     new BsonDocument(
     new BsonDocument(
         "$project",
         "$project",
Ligne 52 : Ligne 52 :
     );
     );


BsonDocument GetSortStage() =>
BsonDocument SortStage() =>
     new BsonDocument("$sort", new BsonDocument("timestamp", 1));
     new BsonDocument("$sort", new BsonDocument("timestamp", 1));
</kode>
</kode>

Version du 20 mars 2024 à 12:47

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();

Pipeline

Cs.svg
var stages = new BsonDocument[]
{
    MatchStage(getTimeSeriesQuery),
    ProjectionStage(),
    SortStage()
};
var pipeline = PipelineDefinition<InputClass, OutputClass>.Create(stages);

var results = (await myCollection.AggregateAsync(pipeline)).List();

BsonDocument MatchStage(GetTimeSeriesQuery getTimeSeriesQuery)
{
    var match = new BsonDocument("property1", "value1");
    if (!string.IsNullOrEmpty(variable2))
    {
        match.AddRange(
            new BsonDocument("property2", variable2)
        );
    }
}

BsonDocument ProjectionStage() =>
    new BsonDocument(
        "$project",
        new BsonDocument
        {
            { "_id", 0 },
            { "property1", 1 },
            { "property2", 1 }
        }
    );

BsonDocument SortStage() =>
    new BsonDocument("$sort", new BsonDocument("timestamp", 1));

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.