Skip to content

Instantly share code, notes, and snippets.

@chrisbck
Created April 8, 2020 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbck/d89de4feb01d96084537e58ebfbcd7d0 to your computer and use it in GitHub Desktop.
Save chrisbck/d89de4feb01d96084537e58ebfbcd7d0 to your computer and use it in GitHub Desktop.
Godot attempt to connect to MongoDb using c# nuget package
using Godot;
using System;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver.Core.Clusters;
public class Mongo : Node
{
MongoCRUD db = new MongoCRUD("testDb"); // MongoDb will get ths database if available, if not it will create it.
public override void _Ready()
{
PersonModel person = new PersonModel
{
FirstName = "Chris",
LastName = "Findlay"
};
db.InsertRecord("Users", person);
}
}
public class MongoCRUD
{
private IMongoDatabase db;
private MongoClient client;
private String ConnectionString = "mongodb://localhost:27017/";
public MongoCRUD(string database)
{
client = new MongoClient(ConnectionString);
//client = new MongoClient();
db = client.GetDatabase(database);
}
public void InsertRecord<T>(string collectionName, T document)
{
IsDatabaseIsConnected(client);
var collection = db.GetCollection<T>(collectionName);
GD.Print("Inserting PersonModel");
try
{
collection.InsertOne(document);
GD.Print("Record Inserted");
}
catch(Exception e)
{
GD.Print("Failed to insertOne()");
//GD.Print(e);
}
}
public bool IsDatabaseIsConnected(MongoClient client)
{
bool isMongoLive = client.Cluster.Description.State == ClusterState.Connected;
if(isMongoLive)
{
GD.Print("connected");
return true;
}
else
{
GD.Print("not connected");
return false;
}
}
}
class PersonModel
{
[BsonId] // _id
public Guid Id {get; set;}
public string FirstName { get; set; }
public string LastName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment