Dec 12, 2021

Your First MongoDB, C# and .NET Core App/My C# and MongoDB Cheat Sheet


Download .NET core SDK

Setup you project and your console project

  1. Select a folder
  2. In the command line: 
    dotnet new console -o console
    dotnet add console package MongoDB.Driver
    cd console
    code console
  3. vsoode will be opened

Create a program.cs file:
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Run the code:
dotnet run


Now add a document and write it
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;


namespace MongoData
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var mongoClient = new MongoClient("MONGODB_URL");
            var mongoDatabase = mongoClient.GetDatabase("trial_db");
            var collection = mongoDatabase.GetCollection<TrialDoc>("trial_cl");

            TrialDoc trialDoc = new TrialDoc();
            trialDoc.BookName = "123";
            collection.InsertOne(trialDoc);
            Console.WriteLine("Done!");
        }
    }

   
    public class TrialDoc
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string? Id { get; set; }

        [BsonElement("Name")]
        public string BookName { get; set; } = null!;

        public int Price { get; set; }

        public string Category { get; set; } = null!;

        public string Author { get; set; } = null!;
    }
}


Add Read Operation: Find All
            var list = collection.Find(_ => true).ToList();
            foreach (var item in list) {
                Console.WriteLine(item.BookName);
            }

Add Read Operation: Specific Record
            var single = collection.Find(x => x.BookName == "123".ToString()).FirstOrDefault();
            Console.WriteLine(single.Id);

Update the record
            collection.ReplaceOne(x => x.Id == single.Id, new TrialDoc() {Id = single.Id, BookName = "456"}, new ReplaceOptions {IsUpsert = true});

var _client = new MongoClient();
var _database = _client.GetDatabase("users");
var counters = _database.GetCollection<BsonDocument>("counters");
var counterQuery = Builders<BsonDocument>.Filter.Eq("_id", "eventId");

var findAndModifyResult = counters.FindOneAndUpdate(counterQuery,
              Builders<BsonDocument>.Update.Set("web", "testweb"));
            FilterDefinition<TrialDoc> filter =
                Builders<TrialDoc>.Filter.Eq(x => x.BookName, "123");
            ProjectionDefinition<TrialDoc> project = Builders<TrialDoc>
                .Projection.Include(x => x.BookName);

            var results = collection.Find(filter).Project(project).ToList();
            foreach (var item in results) {
                Console.WriteLine(item);
            }
Don't forget to create a full text search index first
            var results_list = collection.Find(Builders<TrialDoc>.Filter.Text("123")).ToList();
            foreach (var item in results_list) {
                Console.WriteLine(item);
            }




using MongoDB.Driver.GeoJsonObjectModel;
#Add to document
public GeoJson2DCoordinates Location { get; set; } = null!;
trialDoc.Location = new GeoJson2DCoordinates(31.11, 19.12);
var keys = Builders<BsonDocument>.IndexKeys.Geo2DSphere("Location");
await collection.Indexes.CreateOneAsync(keys);

ShareThis

Intense Debate Comments

Ratings and Recommendations