Mongodb and csharp

De Banane Atomic
Aller à la navigationAller à la recherche

Links

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

Find

Filter

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

filter &= builder.Exists(x => x.Property1);
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.Find(filter).ToListAsync();
var result = (await collection.FindAsync(filter)).ToList();

Handle different types

Cs.svg
// get all the documents
var bsonDocumentCollection = database.GetCollection<BsonDocument>("MyCollection");
var filter = Builders<BsonDocument>.Filter.Empty;
var result = await bsonDocumentCollection.Find(filter).ToListAsync();

// get all the Class1 document
var class1Collection = database.GetCollection<Class1>("MyCollection");
await type1Collection.InsertOneAsync(new Class1 { Name = "Name1" });
var filter = Builders<Class1>.Filter.Eq(x => x.Type, nameof(Class1));
var filter = Builders<SimpleClass>.Filter.Exists(x => x.Name); // get all the documents which have a property Name
var result = await class1Collection.Find(filter).ToListAsync();

class Class1
{
    public ObjectId Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Type { get; set; } =  nameof(Class1);
}

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)
        );
    }
    return new BsonDocument("$match", match);
}

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.

Errors

Requested value '_id' was not found

Cs.svg
await collection.Find(_ => true).ToListAsync();

// query with an id (the objects you want to retrieve must have a property ObjectId Id)
await collection.Find(x => x.Id == new ObjectId("...")).ToListAsync();

Serializer for MyClass does not represent members as fields

Unable to deserialize a document into a Dictionary.

Cs.svg
public class MyClass : Dictionary<string, int>
{
    public ObjectId Id { get; set; }
}

var collection = database.GetCollection<MyClass>(collectionName);
await collection.Find(x => x.Id == new ObjectId("...")).ToListAsync();