- Home /
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.
I'm not sure I follow this thread... and I am very interested in it.
is it about using $$anonymous$$ongo as a network database solution? or is it to use $$anonymous$$ongoDB as a local (in game storage solution)?
I've plenty experience of $$anonymous$$EAN stack and am using REST services in front of a $$anonymous$$ongoDB server. Where I wanted to go next was sync services to a local cache of JSON or BSON data.
In other words I'd like a light version of $$anonymous$$ongoDB that I can build into Unity games with a sync interface to my network server(s).
I might be wrong but at first glance this very interesting thread seems to be covering a mongo client and serialization class to store some data although I can't see where that data gets stored or how I'd access a document from a serialised collection.
Have any of you taken this further or would you like to collaborate ? cheers.
Answer by Romeo-Ordos · Apr 18, 2014 at 10:52 AM
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:
Replace ReadWriteLockSlim with ReadWriteLock in BsonSerializer class.
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);
});
}
}
thanks! your compiled version fixed the issue for me, upvoted
Unity 5 crashes when attempts to initialize $$anonymous$$ongoClient using my dlls from above message.
To get it work you should comment out all calls to "$$anonymous$$arshal.ZeroFreeBSTR(bstr)" within the entire solution or you can just use my updated 1.10 driver from here: http://adf.ly/1VU$$anonymous$$pq
Thanks so much for that! Are you planning to modify the 2.x driver? This would be awesome.
I known that my answer is too late but...
$$anonymous$$ongoDB C# 2.x driver is incompatible with Unity because it supports .Net 4.5 and $$anonymous$$ono 3 only but Unity does not support these platforms.
The latest driver you can use is 1.11. It supports all versions of $$anonymous$$ongoDB from 2.4 to 3.2 and will work with Unity.
Unity just released a new version (2017.1 beta 1) with native .NET 4.6 support.
Does anyone tried to get 2.x drivers for $$anonymous$$ongoDB working with that? https://unity3d.com/de/unity/beta/unity2017.1.0b1
now that Unity 2018.3 is using .Net 4.x and 3 is deprecated, is there any chance of getting a new dll ?
Thanks @Romeo-Ordos
Answer by pparedes · Oct 13, 2015 at 11:31 AM
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...
Answer by radioact1ve · Jan 16, 2014 at 10:37 PM
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 am not familiar with REST so i m not sure yet how to implement this. if you can give some example that would be great basic example should suffice.
did some digging and foudn teh endpoint is: https://api.mongohq.com
but still trying to figure out how to do this. Thanks,
Hmm in that case creating an API might be out of scope. Doing a bit more research, I believe Unity uses $$anonymous$$ono 2.6 and it seems the mongo C# driver doesn't work with that old version? Could be completely wrong here though. Please correct me otherwise!
At this point you might want to verify that the mongo driver actually works with Unity's version of mono. Looks like latest driver was tested on $$anonymous$$ono 2.10.8.
Thanks, ya i also looked at it too and $$anonymous$$ongo drive does not seem to work with unity3d's current build. I'll have a look at REST, it seems simple enough to understand. They seem to be HTTP/S request, I'll scourge the web for examples etc as well.
Thanks agian.
Answer by Masaco · Nov 17, 2014 at 10:08 AM
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.
Answer by --julian95-- · May 01, 2019 at 07:23 PM
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: https://github.com/Julian23517/Unity-mongo-csharp-driver-dlls I try to keep it up to date.
Hi Julian95,
I'm using your dlls and am able to connect to the dB and run queries and I get results, however this only works from the initial Start function. If I try to call the query function again, the collection seems empty or unreachable. This behavior seems strange. Any ideas why the connection will not re-establish in an update ?
Your answer
