Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
2
Indexable
Never
// Open a connection to a MongoDB Atlas cluster using a connection string stored in the environment variable 'CONNECTION_STRING'.

using MongoDB.Bson;
using MongoDB.Driver;

public static class MongoDbHelper
{
    public static IMongoClient GetMongoClient()
    {
        var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new Exception("Missing environment variable 'CONNECTION_STRING'.");
        }

        return new MongoClient(connectionString);
    }
}

// Insert a new document into the database 'database', collection 'people' with the field 'name' set to the value 'Dominic'.
public class Program
{
    public static void Main()
    {
        var mongoClient = MongoDbHelper.GetMongoClient();
        var database = mongoClient.GetDatabase("database");
        var peopleCollection = database.GetCollection<BsonDocument>("people");
        peopleCollection.InsertOne(new BsonDocument("name", "Dominic"));
        
        // In the database 'database', collection ' people', find the document where the field 'name' has the value 'Dominic' and set it to 'Luce'.
        peopleCollection.UpdateOne(new BsonDocument("name", "Dominic"), new BsonDocument("$set", new BsonDocument("name", "Luce")));
        
        // In the database 'database2', collection 'people', find the document where the field 'name' is set to 'Luce'.
        var peopleCollection2 = database.GetCollection<BsonDocument>("people");
        var luce = peopleCollection2.Find(new BsonDocument("name", "Luce")).FirstOrDefault();
        Console.WriteLine(luce);
        
        // Find all documents with the field 'name' set to 'John'.
        var johns = peopleCollection.Find(new BsonDocument("name", "John")).ToList();
        
        // Delete the document where the name field is set to John.
        peopleCollection.DeleteOne(new BsonDocument("name", "John"));
        
        // Push a new value 'foo' into the array 'bars' in all documents.
        peopleCollection.UpdateMany(new BsonDocument(), new BsonDocument("$push", new BsonDocument("bars", "foo")));
        
        // Build an aggregation for the collection 'people'. Match documents with the 'name' being 'John' and project only the 'name' field.
        var pipeline = new BsonArray
        {
            new BsonDocument("$match", new BsonDocument("name", "John")),
            new BsonDocument("$project", new BsonDocument("name", 1))
            
        
    }
}