ssh Github

Mac from Terminal

ssh-keygen -t ed25519 -C "yourmail@domain.com"

output:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/<xxxxx>/.ssh/<yyyy>): /Users/<xxxxx>/.ssh/github_id 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/<xxxxx>/.ssh/github_id
Your public key has been saved in /Users/<xxxxx>/.ssh/github_id.pub
The key fingerprint is:
.....
The key's randomart image is:
+--[ED25519 256]--+
|    ..   .=..    |
|     .o  ..S..   |
|     ..  ..o. . .|
|  . o. ..o . . o |
|   =+...S = . +  |
|  oS.++  o + .   |
|    o+.+    . o  |
|      o..    . . |
|       o..E      |
+----[SHA256]-----+

go to https://github.com/settings/keys

click to New SSH Key

write a title, select Authentication Key, copy content of <yyyy>.pub file to the Key area

Search for a table in all databases in a SQL Server instance

declare @sql nvarchar(max);

select @sql = 
    (select ' UNION ALL
        SELECT ' +  + quotename(name,'''') + ' as database_name,
               s.name COLLATE DATABASE_DEFAULT
                    AS schema_name,
               t.name COLLATE DATABASE_DEFAULT as table_name 
               FROM '+ quotename(name) + '.sys.tables t
               JOIN '+ quotename(name) + '.sys.schemas s
                    on s.schema_id = t.schema_id
            WHERE t.name =''table_name'''

    from sys.databases 
    where state=0
    order by [name] for xml path(''), type).value('.', 'nvarchar(max)');

set @sql = stuff(@sql, 1, 12, '') + ' order by database_name, 
                                               schema_name,
                                               table_name';

execute (@sql);

Find and Kill SQL Server orphaned transactions


select * from sys.sysprocesses where status = 'SLEEPING' and open_tran > 0


-------
declare @sp int
select @sp = spid from sys.sysprocesses where status = 'SLEEPING' and open_tran > 0


if @sp is not null
begin
    declare @tempString nvarchar (255)
    set @tempString = 'kill ' + cast (@sp as varchar (5))
    exec sp_executesql @tempString
end

Git main commands

git config

Usage: git config –global user.name “[name]”  

Usage: git config –global user.email “[email address]”  

This command sets the author name and email address respectively to be used with your commits.

git init

Usage: git init [repository name]

This command is used to start a new repository.

git clone

Usage: git clone [url]  

This command is used to obtain a repository from an existing URL.

git add

Usage: git add [file]  

This command adds a file to the staging area.

Usage: git add .  

This command adds one or more to the staging area.

git commit

Usage: git commit -m “[ Type in the commit message]”  

This command records or snapshots the file permanently in the version history.

Usage: git commit -a  

This command commits any files you’ve added with the git add command and also commits any files you’ve changed since then.

git diff

Usage: git diff  

This command shows the file differences which are not yet staged.

Usage: git diff –staged 

This command shows the differences between the files in the staging area and the latest version present.

Usage: git diff [first branch] [second branch]  

This command shows the differences between the two branches mentioned.

git reset

Usage: git reset [file]  

This command unstages the file, but it preserves the file contents.

Usage: git reset [commit]  

This command undoes all the commits after the specified commit and preserves the changes locally.

Usage: git reset –hard [commit]  This command discards all history and goes back to the specified commit.

git status

Usage: git status  

This command lists all the files that have to be committed.

git rm

Usage: git rm [file]  

This command deletes the file from your working directory and stages the deletion.

git log

Usage: git log  

This command is used to list the version history for the current branch.

Usage: git log –follow[file]  

This command lists version history for a file, including the renaming of files also.

git show

Usage: git show [commit]  

This command shows the metadata and content changes of the specified commit.

git tag

Usage: git tag [commitID]  

This command is used to give tags to the specified commit.

git branch

Usage: git branch  

This command lists all the local branches in the current repository.

Usage: git branch [branch name]  

This command creates a new branch.

Usage: git branch -d [branch name]  

This command deletes the feature branch.

git checkout

Usage: git checkout [branch name]  

This command is used to switch from one branch to another.

Usage: git checkout -b [branch name]  

This command creates a new branch and also switches to it.

git merge

Usage: git merge [branch name]  

This command merges the specified branch’s history into the current branch.

git remote

Usage: git remote add [variable name] [Remote Server Link]  

This command is used to connect your local repository to the remote server.

git remote -v

This command is used to show all remotes.

git push

Usage: git push [variable name] master  

This command sends the committed changes of master branch to your remote repository.

Usage: git push [variable name] [branch]  

This command sends the branch commits to your remote repository.

Usage: git push –all [variable name]  

This command pushes all branches to your remote repository.

Usage: git push [variable name] :[branch name]  

This command deletes a branch on your remote repository.

git pull

Usage: git pull [Repository Link]  

This command fetches and merges changes on the remote server to your working directory.

git stash

Usage: git stash save  

This command temporarily stores all the modified tracked files.

Usage: git stash pop  

This command restores the most recently stashed files.

Usage: git stash list  

This command lists all stashed changesets.

Usage: git stash drop  

This command discards the most recently stashed changeset.

Treeish and Hashes

Rather than a sequential revision ID, Git marks each commit with a SHA-1 hash that is unique to the person committing the changes, the folders, and the files comprising the changeset. This allows commits to be made independent of any central coordinating server.

A full SHA-1 hash is 40 hex characters:
b0c2c709cf57f3fa6e92ab249427726b7a82d221

To efficiently navigate the history of hashes, several symbolic shorthand notations can be used as listed in the table below. Additionally, any unique sub-portion of the hash can be used. Git will let you know when the characters supplied are not enough to be unique. In most cases, 4-5 characters are sufficient.

TREEISHDEFINITION
HEADThe current committed version
HEAD^, HEAD~1One commit ago
HEAD^^, HEAD~2Two commits ago
HEAD~NN commits ago
RELEASE-1.0User defined tag applied to the code when it was certified for release

The complete set of revision specifications can be viewed by typing:

git help rev-parse

Treeish can be used in combination with all Git commands that accept a specific commit or range of commits.

Examples include:

git log HEAD~3..HEAD

git checkout HEAD^^

git merge RELEASE-1.0 

git diff HEAD^..

Viewing

Daily work calls for strong support of viewing current and historical facts about your repository, often from different, perhaps even orthogonal points of view. Git satisfies those demands in spades.

Status

To check the current status of a project’s local directories and files (modified, new, deleted, or untracked) invoke the status command:

git status

Diff

A patch-style view of the difference between the currently edited and committed files, or any two points in the past can easily be summoned. The .. operator signifies a range is being provided. An omitted second element in the range implies a destination of the current committed state, also known as HEAD:

git diff

git diff 32d4

git diff --summary 32d4..

Depending on the Git distribution, a utility called diff-highlight will be included to make diffs easier to visualize by highlighting word-level diffs instead of the default line level changes. Make sure diff-highlight is available in your $PATH and enable it with:

git config --global core.pager "diff-highlight | less -r"

Git allows for diffing between the local files, the stage files, and the committed files with a great deal of precision.

COMMANDDEFINITION
git diffEverything unstaged (not git add’ed) diffed to the last commit
git diff –cachedEverything staged (git add’ed) diffed to the last commit
git diff HEADEverything unstaged and staged diffed to the last commit

Log

The full list of changes since the beginning of time, or optionally, since a certain date is right at your fingertips, even when disconnected from all networks:

git log
git log --since=yesterday $ git log --since=2weeks

Blame

If trying to discover why and when a certain line was added, cut to the chase and have Git annotate each line of a source file with the name and date it was last modified:

git blame <filename.ext>

Best way to use HttpClient

// in Program.cs
builder.Services.AddSingleton<IWeatherClient, OpenWeatherClient>();
builder.Services.AddHttpClient("openWeatherApi", client =>
{
    client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
});

// in OpenWeatherClient.cs
public class OpenWeatherClient : IWeatherClient
{
    private const string OpenWeatherMapApiKey = "";
    private readonly IHttpClientFactory _httpClientFactory;

    public OpenWeatherClient(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<WeatherResponse?> GetCurrentWeatherForCity(string city)
    {
        var client = _httpClientFactory.CreateClient("openWeatherApi");
        return await client.GetFromJsonAsync<WeatherResponse>(
            $"weather?q={city}&appid={OpenWeatherMapApiKey}");
    }
}
// in Program.cs
 builder.Services.AddHttpClient<IWeatherClient, OpenWeatherClient>(client =>
 {
     client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
 });

// in OpenWeatherClient.cs
public class OpenWeatherClient : IWeatherClient
{
    private const string OpenWeatherMapApiKey = "";
    private readonly HttpClient _httpClient;

    public OpenWeatherClientSecond(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<WeatherResponse?> GetCurrentWeatherForCity(string city)
    {
        return await _httpClient.GetFromJsonAsync<WeatherResponse>(
            $"weather?q={city}&appid={OpenWeatherMapApiKey}");
    }
}

C# From String to Stream, and From Stream to String

static void Main( string[] args )
{
    string test = "My sample text";

    // convert string to stream
    byte[] byteArray = Encoding.ASCII.GetBytes( test );
    MemoryStream stream = new MemoryStream( byteArray ); 

    // convert stream to string
    StreamReader reader = new StreamReader( stream );
    string text = reader.ReadToEnd();

    Console.WriteLine( text );
    Console.ReadLine();
}
static void Main( string[] args )
{
    string test = "My sample text";

    // convert string to stream
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter( stream );
    writer.Write( test );
    writer.Flush();

    // convert stream to string
    stream.Position = 0;
    StreamReader reader = new StreamReader( stream );
    string text = reader.ReadToEnd();
}

Oh My Posh | Oh My Zsh

Oh My Posh

Windows

Official website: https://ohmyposh.dev/

NerdFonts: https://www.nerdfonts.com/font-downloads

Installation (https://www.hanselman.com/blog/my-ultimate-powershell-prompt-with-oh-my-posh-and-the-windows-terminal)


Install-Module -Name Terminal-Icons -Repository PSGallery
Install-Module -Name oh-my-posh -RequiredVersion 6.17.0
Get-Module oh-my-posh
Import-Module oh-my-posh
oh-my-posh --init --shell pwsh --config jandedobbleer.omp.json | Invoke-Expression

Microsoft.PowerShell_profile.ps1

Import-Module -Name Terminal-Icons
Import-Module oh-my-posh
cd Powershell/Modules/oh-my-posh
./oh-my-posh --init --shell pwsh --config C:\Users\...\PowerShell\Modules\oh-my-posh\6.17.0\themes\ohmyposhv3-v2.json | Invoke-Expression

MacOs

taken from https://ohmyposh.dev/docs/installation/macos

  • install oh-my-posh with brew
% brew install jandedobbeleer/oh-my-posh/oh-my-posh
% chmod 755 install-nerd-fonts.sh
% install-nerd-fonts.sh
  • run bash with preferred theme
% oh-my-posh prompt init [bash|zsh|fish|powershell|pwsh|cmd|nu] --config ~/.mytheme.omp.json [flags]

------- or ----------

% eval "$(oh-my-posh init bash --config /usr/local/opt/oh-my-posh/themes/atomic.omp.json)"

------- or ----------

% cd $(brew --prefix oh-my-posh)/themes
% eval "$(oh-my-posh init bash --config atomic.omp.json)"

------- or zsh ----------

% eval "$(oh-my-posh init zsh --config /usr/local/opt/oh-my-posh/themes/atomic.omp.json)"

------- or ----------

% eval "$(oh-my-posh init zsh --config ~/.jandedobbeleer.omp.json)"
  • put the command in the .zshrc file

Oh My Zsh

Go to https://ohmyz.sh/ where you can find all instructions:

sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

Install zsh-autosuggestions

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

Linq Grouping examples

I have a collection of items, here it is:

AgencyID VendorID StateID Amount Fee
1        1        1       20.00  5.00
1        1        1       10.00  2.00
1        1        1       30.00  8.00    
2        2        1       20.00  5.00
2        2        1       5.00   5.00
1        1        2       20.00  5.00
2        2        2       20.00  5.00
2        2        2       40.00  9.00
1        2        2       35.00  6.00
1        2        2       12.00  3.00

I’d like these items to be grouped based on the AgencyID, VendorID, and StateID, and the Total calculated from Amount and Fee (Amount + Fee)

So using the data above, I’d like to have these results:

AgencyID VendorID StateID Total
1        1        1       75.00    
2        2        1       35.00
1        1        2       25.00
2        2        2       74.00
1        2        2       56.00
var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

Second Example

public class ConsolidatedChild
{
    public string School { get; set; }
    public string Friend { get; set; }
    public string FavoriteColor { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public string School { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Friend { get; set; }
    public string Mother { get; set; }
    public string FavoriteColor { get; set; }
}
var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

MongoDB Test projections

I have to test this:

using MongoDB;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;

var connectionString = "mongodb://user:pass@xxx.mongolab.com:53139/xxx";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("xxx");
                    
var courses = database.GetCollection("Course");

//Option A (without any where clause)
 var course =courses.FindAllAs<Course>().SetFields(Fields.Include("Title", "Description").Exclude("_id")).ToList();
 //Option B (with where clause)
 var course = courses.FindAs<Course>(MongoDB.Driver.Builders.Query.EQ("Title", "Todays Course")).SetFields(Fields.Include("Title", "Description").Exclude("_id")).ToList();
 
 //Option C (with where clause). Its an alternative approach of Option B.
  var query = new QueryDocument("Title", "Todays Course");
  var course = courses.FindAs<Course>(query1).SetFields("Title","Description").ToList();

C# MongoDB tutorial

MongoDB

MongoDB is a NoSQL cross-platform document-oriented database. It is one of the most popular databases available. MongoDB is developed by MongoDB Inc. and is published as free and open-source software.https://ff935c8ad059c2ed9c66a1f419887c88.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections. Collections are analogous to tables in relational databases and documents to rows.

MongoDB represents JSON documents in binary-encoded format called BSON behind the scenes. BSON extends the JSON model to provide additional data types, ordered fields, and to be efficient for encoding and decoding within different languages. The .NET driver uses BsonDocument to represent BSON.

MongoDB.Driver

MongoDB.Driver is the fficial .NET driver for MongoDB.

$ dotnet add package MongoDB.Driver

We need to add the MongoDB.Driver package to each .NET Core project.

MongoDB create database

The mongo tool is an interactive JavaScript shell interface to MongoDB, which provides an interface for systems administrators as well as a way for developers to test queries and operations directly with the database.

$ mongo testdb
MongoDB shell version v4.0.7
connecting to: mongodb://127.0.0.1:27017/testdb?gssapiServiceName=mongodb
...
> db
testdb
> db.cars.insert({name: "Audi", price: 52642})
> db.cars.insert({name: "Mercedes", price: 57127})
> db.cars.insert({name: "Skoda", price: 9000})
> db.cars.insert({name: "Volvo", price: 29000})
> db.cars.insert({name: "Bentley", price: 350000})
> db.cars.insert({name: "Citroen", price: 21000})
> db.cars.insert({name: "Hummer", price: 41400})
> db.cars.insert({name: "Volkswagen", price: 21600})

We create a testdb database and insert eight documents in the cars collection. We will work with this data in the tutorial.

C# MongoDB list databases

The first example connects to the MongoDB server and retrieves its databases.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace SimpleEx
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var dbList = dbClient.ListDatabases().ToList();

            Console.WriteLine("The list of databases are:");

            foreach (var item in dbList)
            {
                Console.WriteLine(item);
            }
        }
    }
}

The example connects to the MongoDB server and retrieves all its databases.

var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

MongoClient class is used to connect to the MongoDB server. The 27017 is the default port on which the MongoDB server listens.

var dbList = dbClient.ListDatabases().ToList();

We get the list of the databases with the ListDatabases method.

foreach (var item in dbList)
{
    Console.WriteLine(item);
}

We go through the list and print the items.

$ dotnet run
The list of databases are:
{ "name" : "admin", "sizeOnDisk" : 32768.0, "empty" : false }
{ "name" : "config", "sizeOnDisk" : 86016.0, "empty" : false }
{ "name" : "local", "sizeOnDisk" : 81920.0, "empty" : false }
{ "name" : "test", "sizeOnDisk" : 212992.0, "empty" : false }
{ "name" : "testdb", "sizeOnDisk" : 155648.0, "empty" : false }

C# MongoDB RunCommand

The RunCommand method runs a command on the database.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace MongoCommand
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var command = new BsonDocument { { "dbstats", 1 } };
            var result = db.RunCommand<BsonDocument>(command);
            Console.WriteLine(result.ToJson());
        }
    }
}

The example connects to the testdb database and gets its statistics.

IMongoDatabase db = dbClient.GetDatabase("testdb");

We get the database with the GetDatabase method.

var command = new BsonDocument { { "dbstats", 1 } };
var result = db.RunCommand<BsonDocument>(command);

With the RunCommand method, we execute the dbstats command. The command returns a document which is a representation of a MongoDB document.

Console.WriteLine(result.ToJson());

We print the document to the console in the JSON format.

$ dotnet run
{ "db" : "testdb", "collections" : 3, "views" : 0, "objects" : 15, "avgObjSize" : 57.0,
"dataSize" : 855.0, "storageSize" : 77824.0, "numExtents" : 0, "indexes" : 3,
"indexSize" : 77824.0, "fsUsedSize" : 160688828416.0, "fsTotalSize" : 254721126400.0, "ok" : 1.0 }

C# MongoDB find document

We query for a document with a specific filter. The filter is given to the Find method, which looks for a document applying the given filter.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace FindDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");
            var cars = db.GetCollection<BsonDocument>("cars");

            var filter = Builders<BsonDocument>.Filter.Eq("price", 29000);

            var doc = cars.Find(filter).FirstOrDefault();
            Console.WriteLine(doc.ToString());
        }
    }
}

The example finds a document with a car whose price is 29000.

var cars = db.GetCollection<BsonDocument>("cars");

We get the cars collection with the GetCollection method.

var filter = Builders<BsonDocument>.Filter.Eq("price", 29000);

A filter is created; we look for a car with price equal to 29000.

var doc = cars.Find(filter).FirstOrDefault();

We pass the filter to the Find method and retrieve it with the FirstOrDefault method.

$ dotnet run
{ "_id" : ObjectId("5d4d1408463315268eb7376e"), "name" : "Volvo", "price" : 29000.0 }

C# MongoDB find all documents

If we do not specify a filter condition for the Find method, we get all documents.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace FindAll
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");
            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");
            var documents = cars.Find(new BsonDocument()).ToList();

            foreach (BsonDocument doc in documents)
            {
                Console.WriteLine(doc.ToString());
            }
        }
    }
}

The example retrieves all documents from the cars collection.

$ dotnet run
{ "_id" : ObjectId("5d4d13d6463315268eb7376b"), "name" : "Audi", "price" : 52000 }
{ "_id" : ObjectId("5d4d13f5463315268eb7376c"), "name" : "Mercedes", "price" : 57127.0 }
{ "_id" : ObjectId("5d4d1408463315268eb7376e"), "name" : "Volvo", "price" : 29000.0 }
{ "_id" : ObjectId("5d4d140d463315268eb7376f"), "name" : "Bentley", "price" : 350000.0 }
{ "_id" : ObjectId("5d4d1411463315268eb73770"), "name" : "Citroen", "price" : 21000.0 }
{ "_id" : ObjectId("5d4d1415463315268eb73771"), "name" : "Hummer", "price" : 41400.0 }
{ "_id" : ObjectId("5d4d1419463315268eb73772"), "name" : "Volkswagen", "price" : 21600.0 }

We get all seven documents.

C# MongoDB query

Mongo support several query filtering operators such as GtLt, or Gte.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace MongoQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");
            var cars = db.GetCollection<BsonDocument>("cars");

            var builder = Builders<BsonDocument>.Filter;
            var filter = builder.Gt("price", 30000) & builder.Lt("price", 55000);

            var docs = cars.Find(filter).ToList();

            docs.ForEach(doc => {
                Console.WriteLine(doc);
            });
        }
    }
}

The example prints all documents whose car prices are between 30000 and 55000.

var filter = builder.Gt("price", 30000) & builder.Lt("price", 55000);

We build a filter with two operators: Gt and Lt.

$ dotnet run
{ "_id" : ObjectId("5d4d13d6463315268eb7376b"), "name" : "Audi", "price" : 52000 }
{ "_id" : ObjectId("5d4d1415463315268eb73771"), "name" : "Hummer", "price" : 41400.0 }

We have found two documents that match the criteria.

C# MongoDB insert document

A new document is inserted into the collection with the InsertOne method.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace InsertDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");

            var doc = new BsonDocument
            {
                {"name", "BMW"},
                {"price", 34621}
            };

            cars.InsertOne(doc);
        }
    }
}

The example inserts a new car document into the cars collection.

var doc = new BsonDocument
{
    {"name", "BMW"},
    {"price", 34621}
};

A new BsonDocument is created.

cars.InsertOne(doc);

The document is inserted into the collection with the InsertOne method.

C# MongoDB skip and limit

The limit query option specifies the number of documents to be returned and the skip option skips the specified number of documents.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace LimitSkip
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");
            var docs = cars.Find(new BsonDocument()).Skip(3).Limit(3).ToList();

            docs.ForEach(doc =>
            {
                Console.WriteLine(doc);
            });
        }
    }
}

The example reads from the testdb.cars collection, skips the first three documents, and limits the output to three documents.

$ dotnet run
{ "_id" : ObjectId("5d4d140d463315268eb7376f"), "name" : "Bentley", "price" : 350000.0 }
{ "_id" : ObjectId("5d4d1411463315268eb73770"), "name" : "Citroen", "price" : 21000.0 }
{ "_id" : ObjectId("5d4d1415463315268eb73771"), "name" : "Hummer", "price" : 41400.0 }

The output contains three documents.

C# MongoDB projections

Projections determine which fields are going to be included in the query output.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace Projections
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");
            var docs = cars.Find(new BsonDocument()).Project("{_id: 0}").ToList();

            docs.ForEach(doc =>
            {
                Console.WriteLine(doc);
            });
        }
    }
}

In the example, we find all documents. We exclude the _id from the output.

$ dotnet run
{ "name" : "Audi", "price" : 52000 }
{ "name" : "Mercedes", "price" : 57127.0 }
{ "name" : "Volvo", "price" : 29000.0 }
{ "name" : "Bentley", "price" : 350000.0 }
{ "name" : "Citroen", "price" : 21000.0 }
{ "name" : "Hummer", "price" : 41400.0 }
{ "name" : "Volkswagen", "price" : 21600.0 }

The output of the documents does not contain the _id field.

C# MongoDB delete document

A document is deleted with the deleteOne method.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace DeleteDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");
            var filter = Builders<BsonDocument>.Filter.Eq("name", "BMW");

            cars.DeleteOne(filter);
        }
    }
}

The example deletes a document whose car name is BMW.

C# MongoDB update document

A document is updated with the UpdateOne method.Program.cs

using MongoDB.Driver;
using MongoDB.Bson;

namespace UpdateDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://127.0.0.1:27017");

            IMongoDatabase db = dbClient.GetDatabase("testdb");

            var cars = db.GetCollection<BsonDocument>("cars");

            var filter = Builders<BsonDocument>.Filter.Eq("name", "Audi");
            var update = Builders<BsonDocument>.Update.Set("price", 52000);

            cars.UpdateOne(filter, update);
        }
    }
}

The example updates a car document whose name is Audi. It sets a new price for this document.

cars.UpdateOne(filter, update);

The UpdateOne method takes a filter to find the exact document and the update operation to perform the actual change.

In this tutorial, we have worked with MongoDB in C#.