This week I started to read an understand how Couchbase works and that’s the reason I decided to write: Step by step: Couchbase with .Net Core

Tip: I’ll be using Docker to install and run Couchbase

Now let’s start:

Create a folder for your new project


Open a command prompt an run

1mkdir couchbase.console
2cd couchbase.console

Create a console project


1dotnet new console

Add the Couchbase nuget package


Add the Couchbase nuget package to your project:

1dotnet add package CouchbaseNetClient
2dotnet restore

Replace the contents of Program.cs


Replace the contents of the Program.cs file with the following code:

 1namespace couchbase.console
 2{
 3    using System;
 4    using Couchbase;
 5
 6    class Program
 7    {
 8        static void Main(string[] args)
 9        {
10            // Connect to cluster. Defaults to localhost
11            using (var cluster = new Cluster())
12            {
13                // Open the beer sample bucket
14                using (var bucket = cluster.OpenBucket("beer-sample"))
15                {
16                    // Create a new beer document
17                    var document = new Document<dynamic>
18                    {
19                        Id = "Polar Ice",
20                        Content = new
21                        {
22                            name = "Polar Ice",
23                            brewery_id = "Polar"
24                        }
25                    };
26
27                    // Insert the beer document
28                    var result = bucket.Insert(document);
29                    if (result.Success)
30                    {
31                        Console.WriteLine("Inserted document '{0}'", document.Id);
32                    }
33
34                    // Query the beer sample bucket and find the beer we just added.
35                    using (var queryResult = bucket.Query<dynamic>("SELECT name FROM `beer-sample` WHERE brewery_id =\"Polar\""))
36                    {
37                        foreach (var row in queryResult.Rows)
38                        {
39                            Console.WriteLine(row);
40                        }
41                    }
42                }
43            }
44        }
45    }
46}

Setup Couchbase with Docker


Run the following commands:

1docker pull couchbase/server
2docker run -d --name db -p 8091-8094:8091-8094 -p 11210:11210 couchbase

Browse to: http://localhost:8091 and setup Couchbase.

Be sure to add the Beer Sample bucket and check the documentation here: https://hub.docker.com/r/couchbase/server/

Run the program


Run the program and enjoy!

1dotnet run

Get the code here: https://github.com/cmendible/dotnetcore.samples/tree/main/couchbase.console

Hope it helps!