[Unity VR] Connect MongoDB with unity

2016-06-18

This article is going to illustrate how to connect MongoDB with unity. Besides, I will write another article about how to connect MYSQL with unity as well.

I have put all the material and source code on Github, here is the link: (https://github.com/Hanslen/unityWithMongodb/tree/master)

Import packages:

First you need to import the unity+mongodb.unitypackage, which is in the Github link. You can download, it contains “MongoDB.Bson.dll” and “MongoDB.Driver.dll”.

Writing script to connect with MongoDB:

Firstly, I create an empty object and link it with a script. In that script, you need to include these

1
2
3
4
5
6
7
8
9
10
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;

These you ensure you can use that packages, then, modify the main class. For this example, I write like these:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class HelloMongo : MonoBehaviour {
string connectionString = "mongodb://localhost:27017";
void Start () {
/*
* Establish connection
*/
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("unity");
var shopCollection= database.GetCollection("vrshop");
Debug.Log ("ESTABLISHED CONNECTION");
}
}

The connectionString stands for the mongodb host, you can check your host by looking at your ./mongod(for mac) or mongod.exe(for windows):
mo

Query collections:

To get all the collections, you can use:

1
2
3
foreach (var document in shopCollections.FindAll()) {
Debug.Log ("My vrshop \n" + document);
}

If you just want to find one accurate row, use:

1
2
3
foreach (var document in shopcollections.Find(new QueryDocument("name", "nike"))){
Debug.Log ("Get one info: \n" + document);
}

If you want to select the first row, use:

1
Debug.Log("First row: \n" + shopCollections.FindOne ().ToString());

If you want to select the column where name = “nike”, use:

1
2
3
foreach (var document in shopCollections .Find(new QueryDocument("name", "nike"))){
Debug.Log ("Select one column where name=nike: \n" + document["scores"]);
}

Insert into Collections:

The following code is a sample with inserting several lines of data, if you want to insert one line, it’s the same, code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
BsonDocument [] batch={
new BsonDocument{
{"name", "nike"},
{"price", "100"}
},
new BsonDocument{
{"name", "adidas"},
{"price", "200"}
},
new BsonDocument{
{"name", "Lining"},
{"price", "300"}
}
};
shopcollections.InsertBatch (batch);

There are some more advanced querying data code, which will be in the file advanced.cs. You can check that out. Enjoy your unity journey with MongoDB. Thanks for reading. 🙂

Many thanks for fabifiess who shared his code on GitHub.


Comments: