DEV Community

Cover image for Tutorial: MongoDB With C# The Easy Way!

Tutorial: MongoDB With C# The Easy Way!

Dĵ ΝιΓΞΗΛψΚ on January 01, 2020

the goal of this article is to familiarize you with an alternative, less verbose & convenient way to store and retrieve data in MongoDB server ...
Collapse
 
anthopark profile image
Anthony Park • Edited

Thank you so much for this beautiful wrapper library. I'm about to use this library in my next project and was wondering how the DI scoping works with the DB connection.

I'm used to the idea of having a DBContext that is scoped lifecycle and use that DBContext in a repository object, which I also register in a DI container as the scoped.

Would you recommend making a repository class that uses DB? If so, how does the lifecycle works?

Collapse
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

you're most welcome. i believe this bit of info from the documentation answers your question. specifically, have a look at the repository pattern sample project link.

Collapse
 
anthopark profile image
Anthony Park • Edited

This tremendously helped! I'm now thinking of testing a service object that depends on the repository. I'm thinking of try DB.InitAsync with mongo2go in the xunit project and was wondering if you have some suggestions around the right way to mocking the DB connection with your library.. Thanks a ton!

Thread Thread
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

integration testing is the recommended approach. something like this if it's a web api project.

however I think doing db.initasync with mongo2go address in the setup/class fixture should do the trick.

let me know if it doesn't and I'll have a deeper look.

Thread Thread
 
anthopark profile image
Anthony Park

Thanks for the quick response! I was able to connect to Mongo2Go with your library but came across an issue which I've described in your repo issues.

I think I may need to use Xunit's class fixture and persist the connection throughout the test cases in a test class.

Collapse
 
catalinradoi profile image
CatalinRadoi

Hi. Shouldn't "new DB()" be assigned to an object or something?

Collapse
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

not necessary if you're only dealing with a single database. if dealing with multiple dbs, then you need to assign to a variable as shown here.

Collapse
 
catalinradoi profile image
CatalinRadoi

Thanks! One more question :P I'm a MongoDB Newbie

I have an entity called Zone, with only one property: public int SqlId { get;set; }

And I have an entity Search:
public class Search : Entity {
public Many Zones { get; set; }
public Search() => this.InitOneToMany(() => this.Zones);
}

this is how an add a new Search:

var search = new Search();
search.Save();
var zone1 = new Zone { SqlId = 1};
zone1.Save();

search.Zones.Add(zone1);

var zone2 = new Zone { SqlId = 2};
zone2.Save();
search.Zones.Add(zone2);

search.Save();

I have multiple issues:

  1. Zones are duplicated in MongoDb. A new document is created for each new SqlId.

I wanted to use the Id from Mongo, but I can't "overwrite" that one. Then I need to make this SqlId unique or something.

  1. There seem to be a lot of "saves" is this good (performance-wise)?
Thread Thread
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

you can do bulk saves like this:

            var zones = new[] {
                new Zone { SqlId = 1 },
                new Zone { SqlId = 2 }
            };

            DB.Save(zones);

            var search = new Search();
            search.Save();

            search.Zones.Add(zones);

Zones are duplicated in MongoDb. A new document is created for each new SqlId.

i don't really understand your requirement here. do you not want to create two new zone documents?

Thread Thread
 
catalinradoi profile image
CatalinRadoi

Thanks for answering, you are awesome :)

no, I don't want to create two new zones.
Zones are like a META table or "Dictionary".

I only have 20 zones, from id = 1 to id = 20

A search could have a combination of these zones.
1, 2
or 1,2,3

I want to create two new Search documents, but I don't want the Zones to be created each time.

Thread Thread
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

for seeding the zone entities once, you can use the migrations feature by first writing a migration class like this:

public class _001_seed_zone_data : IMigration
{
    public void Upgrade()
    {
        var zones = new List<Zone>();

        for (int i = 1; i <= 20; i++)
        {
            zones.Add(new Zone { SqlId = i });
        }

        zones.Save();
    }
}

then on your application startup simply call:

    DB.Migrate();

then you can create your searches like this:

    var wantedZones = new[] { 1, 2, 3 };

    var foundZones = DB.Find<Zone>()
                       .Many(z => wantedZones.Contains(z.SqlId));

    var seach1Zones = foundZones.Where(z => new[] { 1, 2 }.Contains(z.SqlId));
    var search2Zones = foundZones.Where(z => new[] { 1, 2, 3 }.Contains(z.SqlId));

    var search1 = new Search();
    var search2 = new Search();

    DB.Save(new[] { search1, search2 });

    search1.Zones.Add(seach1Zones);
    search2.Zones.Add(search2Zones);
Thread Thread
 
catalinradoi profile image
CatalinRadoi

Thanks, you are very cool. I will try it now

Thread Thread
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

here's my test program in case you need to have a look: gist.github.com/dj-nitehawk/8bde0d...

Thread Thread
 
catalinradoi profile image
CatalinRadoi

Thank you :) I bought you a coffee for your outstanding help.

This project has a lot of potentials! I will recommend it to fellow C# devs.

Thread Thread
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

you are most welcome. just received the email notification regarding the donation. much appreciated. if you ever need any more help, just go to the github repo and open up a new issue. i'll be more than glad to help. have a great day!

Collapse
 
reachej profile image
Erik • Edited

I'm trying to use MongoDB.Entities in Uipath Studio via the Invoke code activity. I was unable to get the connection initialized until I did this (the instructions are wrong on the website):

string connectionstring = "mongodb+srv://m220student:m220password@mflix.XXXXX.mongodb.net/mflix?retryWrites=true&w=majority";
Console.WriteLine("connection string :"+ connectionstring);
string databasename = "mflix";
DB.InitAsync(databasename,MongoClientSettings.FromConnectionString(connectionstring));
Console.WriteLine("initialized");

Now I'm trying to figure out how to select a database and create a document in a collection. In the invoke code activity in uipath, if you have the word await it won't compile and if you declare a class it won't compile.

Collapse
 
feddessi profile image
Federico Dessì • Edited

Hi, I've read through your documentation but I can't find what I'm looking for. In the official MongoDB driver you can specify if you want your ID to be a specific field instead of the generic ObjectID, how can I do the same here?

I'll be more specific: In your Wiki you give the example of a Book entity, I would like to specify the _id field to be the ISBN number (for example) instead of auto generating a mongo ObjectID. Is this possible?

Collapse
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

with this library it's not possible to change the type of the default id as objectid was chosen to be the best option for >90% of cases. you can however simply add another property to store the ISBN and put an index on it so queries can be written on that instead of querying by the ID. imho it's a small price to pay considering the benefits offered by the library.

Collapse
 
adie305 profile image
Adie305

Hi. How to make C# Windows Form Login using mongodb?

Collapse
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

sorry mate cannot help you there as I haven't worked with winforms in over 10yrs. but the data access logic is the same. just use the DB static class to store and retrieve your entities as explained in the tutorial.