Unity And MongoDB (SaaS)

Hi,

Has anyone has any success in implementing MongoDB (say from mongohq.com) with unity?
I’ve scratched my head and still cannot figure out why and is hoping someone could possible ran across this and have some input.

using UnityEngine;
using MongoDB.Driver.Builders;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;

public class Examples : MonoBehaviour {

		
	void OnGUI()
	{
		if (GUI.Button (new Rect (20,70,80,20), "Button")) {
			doTest();
		}
	}
	void doTest()
	{
		MongoClient client=new MongoClient("mongodb://user:password@widmore.mongohq.com:10000/InitialDB");
		MongoServer server = client.GetServer();
		MongoDatabase db = server.GetDatabase("InitialDB");
		MongoCollection<Weapons>  tblWeapons= db.GetCollection<Weapons>("Weapons");
		Debug.Log (db.CollectionExists ("Weapons").ToString ());
	}

}

public class Weapons : MonoBehaviour {

// Use this for initialization
	[MongoDB.Bson.Serialization.Attributes.BsonElement]
	public ObjectId _id { get; set; }
	[MongoDB.Bson.Serialization.Attributes.BsonElement]
	public string _Name { get; set; }
	[MongoDB.Bson.Serialization.Attributes.BsonElement]
	public int _PhysicalPower { get; set; }
	[MongoDB.Bson.Serialization.Attributes.BsonElement]
	public int _MagicPower { get; set; }

}

I ran the ‘doTest()’ function in Visual Studio C# and do get a response back from the MessageBox.Show() instead of Debug.Log() as opposed to unity.

The two class also compile in mono without an issue.

When i play and press the button:

NotImplementedException: recursionPolicy != NoRecursion not currently implemented
System.Threading.ReaderWriterLockSlim..ctor (LockRecursionPolicy recursionPolicy)
MongoDB.Bson.Serialization.BsonSerializer..cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for MongoDB.Bson.Serialization.BsonSerializer
MongoDB.Driver.MongoCollection.FindAs[BsonDocument] (IMongoQuery query)
MongoDB.Driver.MongoCollection.FindAllAs[BsonDocument] ()
MongoDB.Driver.MongoCollection`1[MongoDB.Bson.BsonDocument].FindAll ()
MongoDB.Driver.MongoDatabase.GetCollectionNames ()
MongoDB.Driver.MongoDatabase.CollectionExists (System.String collectionName)
Examples.doTest () (at Assets/Examples.cs:24)
Examples.OnGUI () (at Assets/Examples.cs:15)

This is what i m getting.
reviewing the error, i think the BSonSerializer is the cause of the problem but only to the UnityEditor and not Visual Studio.

Anyone has any input or suggestion on trying to get this to connect to the MongoDB?

Also, the db is as mention on a cloud hosted by MongoHQ.

Thanks,

Hoang.

As your stacktrace says NoRecusion isn’t present in Unity’s current Mono. The workaround is to build mongo driver yourself using source code from github.

You should change two things to make it work with Unity:

  1. Replace ReadWriteLockSlim with ReadWriteLock in BsonSerializer class.
  2. Remove all calls to Marshal.ZeroFreeBSTR from the solution.

Or you can use my own builds:

This driver requires .NET 2.0 API Compability level and will not work with .NET 2.0 Subset.

I have checked it with Unity 4.2.2 and 5.4.4 with UnityThreadHelper running 100 threads inserting 100000 entries to localhost and mlab.com MongoDB without any issues.

using System;
using MongoDB.Bson;
using MongoDB.Driver;
using UnityEngine;
using Random = UnityEngine.Random;

public class Mongo : MonoBehaviour
{
    public class Order
    {
        public enum STATE : byte
        {
            NEW = 0,
            CANCELLED = 1,
            COMPLETE = 2
        }

        public ObjectId Id { get; set; }
        public string account { get; set; }
        public string sku { get; set; }
        public STATE state { get; set; }
        public DateTime created { get; set; }
        public string token { get; set; }
    }

    private MongoClient client;
    private MongoServer server;
    private MongoDatabase db;
    private MongoCollection<Order> orders;

    private int counter = 0;
    private bool work = true;
    protected void Start () 
    {
        client = new MongoClient(new MongoUrl("mongodb://localhost"));
        server = client.GetServer();
        server.Connect();
        db = server.GetDatabase("local");
        orders = db.GetCollection<Order>("order");

        for (var i = 0; i < 100; i++)
        {
            InsertRandomDocument();
        }
    }

    protected void OnGUI()
    {
        GUI.Label(new Rect(40, 40, 200, 20), "Inserts: " + counter);
        if (GUI.Button(new Rect(40, 70, 200, 20), "Stop"))
            work = false;
    }

    private void InsertRandomDocument()
    {
        var order = new Order
        {
            account = Utils.RandomString(6),
            sku = Utils.RandomString(6),
            state = (Order.STATE) Random.Range(0, 3),
            created = DateTime.Now,
            token = Utils.RandomString(50)
        };

        UnityThreadHelper.TaskDistributor.Dispatch(() =>
        {
            orders.Insert(order);
            System.Threading.Thread.Sleep(10);
            if (System.Threading.Interlocked.Increment(ref counter) < 100000 && work)
                UnityThreadHelper.Dispatcher.Dispatch(InsertRandomDocument);
        });
    }
}

This post was very helpful to get Mongo working within my Unity Project. Also thanks to the link to the drivers for Mongo for Unity 5. For others that are starting, @Romeo’s post explains the process generally but I am adding some very basic help in case it’s not obvious.

  • In order to add Romeo’s drivers, you need to create a Plugins folder under Assets and place the downloaded drivers/files in that new folder
  • UnityThreadHelper.TaskDistributor code is from UnityThreadHelper and can be found in the Asset Store
  • I agree with @radioact1ve that creating an API is probably better so it doesn’t matter what database you use but, you can go crazy integrating RESTful API’s, hosted databases and hosted application platforms. I’m still not sure where to securely store any database credentials in Unity that can be deployed easily.
  • Also found this references to the c# libraries, in case folks are wondering about update and other queries.
  • BTW I was using Robomongo to keep track of the databases and collections, however when connecting to the “local” database it wasn’t refreshing so I thought it wasn’t working, just needed to change to “test” or another database and click refresh (definitely my user error).

Hope this helps others searching via google…

I have very limited knowledge of mongo and zero Unity+mongo. Has the mongo driver been tested on mono? This might be a little OT but I wanted to suggest:

Why not create/use/provide a RESTful API, which hides the mongo details, that you’d call from unity code? That way there is zero mongo code directly in the unity app and it doesn’t even need to know what DB is being used.

Does that make sense? Sorry I couldn’t provide help to the problem at hand.

I have figured out how to run MongoDb in .Net 4.x. (Unity 18.3 and 19.1 tested)
You have to Include these dlls in a Plugins folder:

DnsClient.dll  
MongoDB.Bson.dll  
MongoDB.Driver.Core.dll  
MongoDB.Driver.dll  
System.Buffers.dll  

To connect to the Database (replace username, password, DATABASE_NAME and localhost (localhost only, if you host your database elsewhere)):

using MongoDB.Driver;

private const string MONGO_URI = "mongodb://username:password@localhost:27017";
private const string DATABASE_NAME = "testDatabase";
private MongoClient client;
private IMongoDatabase db;

client = new MongoClient(MONGO_URI);
db = client.GetDatabase(DATABASE_NAME);

You can download the dlls at my github: GitHub - Julian23517/Unity-mongo-csharp-driver-dlls I try to keep it up to date.

Romeo’s nice example above works well on development mode. Building the app causes errors: “Assembly WindowsBase is referenced by MongoDB.Bson”.

I got build working by changing API Compatibility Level buildsettings/playersettings/othersettings from ‘.net2.0 subset’ to ‘.net2.0’.
So now everything runs perfectly!

Setup used: Romeo’s build of v1.8.3 driver, Macosx universal, Unity 4.5.4, Mongodb 2.4.4, mongolab.

What I did and Worked!! (2021)

  1. *Created in Visual Studio a console application, then Download via NuGet
    the MongoDB Driver
  2. In VS - SolutionExplorer - Dependencies - Packages - (RightClick) Open folders in Win File Explorer
  3. There you’ll find all necessary DLL’s! (Lib folder)
  4. Required dlls for Mongo to work in unity → DnsClient/SharpCompress/System.Buffers/MongoDB.Bson/MongoDBDriver.Core/MongoDBDriver/Syste.Runime.CompileServices.Unsafe
  5. Add to Unity’s Plugins + One Assembly Definitions for all your Scripts folder + Set DLL’s as required references
  6. ENJOY!
    @masaco thanks for the initial guideline!!