1

我正在制作一个游戏,其中在不同的多人服务器中有工具包。玩家可以购买套件,并将其保存到 Mongo 数据库中。我希望数据库的格式如下:

{
    "server": "the_server_name",
    "players": {
        {
            "player": "the_players_username",
            "kits": [
                "kit1",
                "kit3"
            ]
        },
        {
            "player": "the_players_username",
            "kits": [
                "kit1",
                "kit2"
            ]
        }
    }
}

我试过这样做没有用。有人愿意为初学者提供一些关于如何实现这一目标的帮助吗?谢谢!

4

1 回答 1

2

这是一个简单的例子:

import com.mongodb.*;

public class MongoTest {

    public static void main(String[] args) throws Exception {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("myGameDB");
        DBCollection gameCollection = db.getCollection("myGameCollection");
        BasicDBObject obj = new BasicDBObject().append("sever", "the_server_name");
        BasicDBList players = new BasicDBList();
        BasicDBList list1 = new BasicDBList();
        BasicDBList list2 = new BasicDBList();
        list1.addAll(java.util.Arrays.asList(new String[]{"kit1", "kit2"}));
        list2.addAll(java.util.Arrays.asList(new String[]{"kit1", "kit2"}));
        BasicDBObject playerObj1 = new BasicDBObject("player", "the_players_username").append("kits", list1);
        BasicDBObject playerObj2 = new BasicDBObject("player", "the_players_username").append("kits", list2);
        players.add(playerObj1);
        players.add(playerObj2);
        obj.append("players", players);
        gameCollection.insert(obj);
        printCollectionContent(gameCollection);
    }


    static void printCollectionContent(DBCollection coll) {
        BasicDBObject query = new BasicDBObject();
        BasicDBObject fields = new BasicDBObject("server", true).append("_id", false).append("players",true);
        DBCursor curs = coll.find(query);
        while (curs.hasNext()) {
            DBObject o = curs.next();
            System.out.println(o.toString());
        }
        curs = coll.find(query, fields);
        while (curs.hasNext()) {
            DBObject o = curs.next();
            System.out.println(o.toString());
        }
    }
}

顺便说一句,你json实际上是无效的。Players 似乎是一个数组,但它缺少一个[ ]

此示例使用2.11.3. 示例是为了展示如何使用驱动程序,省略了异常处理。

于 2014-02-18T08:46:32.320 回答