MongoDB使用java从文档中的对象获取数据

h9a6wy2h  于 2022-12-26  发布在  Go
关注(0)|答案(1)|浏览(209)

我的数据库中有以下文档:

_id: ObjectId('63a73aec1afb1e4de760d9de')
uuid: "71e5db4e-ab05-4de2-9238-5660474c5156"
coins: 0
level: 1
currentXp: 1
upgrades: Object
   durability: 0
   luck: 1

现在我想从对象中获取数据,我试着通过以下方式从持久性中获取int:

public static int getDurabilityLevel(UUID uuid) {
    Document filter = new Document("uuid", uuid.toString());

    int durabilityLevel = Main.getInstance().getDataConnection().getCollection().find(filter).first().getInteger("upgrades.durability");

    return durabilityLevel;
}

我还想对luck整数的值进行chance运算,但是如果我尝试chance运算,durability整数就会消失,我用下面的方法来对值进行chance运算:

public static void setLuckLevel(UUID uuid, int level) {
    Document filter = new Document("uuid", uuid.toString());

    Document foundDocument = Main.getInstance().getDataConnection().getCollection().find(filter).first();

    if(foundDocument != null) {
        Document updateValue = new Document("Upgrades", new Document("luck", level));
        Document updateOperation = new Document("$set", updateValue);

        Main.getInstance().getDataConnection().getCollection().updateOne(foundDocument, updateOperation);
    }
}

我希望任何人能帮助我解决这个简单的问题。谢谢!

2guxujil

2guxujil1#

现在我可以解决这些问题了。以下是我的解决方案:
这是我从对象获取数据的方法:

public static int getDurabilityLevel(UUID uuid) {
    Document filter = new Document("uuid", uuid.toString());

    Document document = Main.getInstance().getDataConnection().getCollection().find(filter).first();
    Document object = (Document) document.get("upgrades");

    int durabilityLevel = object.getInteger("durability");

    return durabilityLevel;
}

这就是我在不删除其他值的情况下对对象中的数据进行随机化的方法:

public static void setDurabilityLevel(UUID uuid, int level) {
    Document filter = new Document("uuid", uuid.toString());

    Document foundDocument = Main.getInstance().getDataConnection().getCollection().find(filter).first();

    if (foundDocument != null) {
        Document updateValue = new Document("upgrades.durability", level);
        Document updateOperation = new Document("$set", updateValue);

        Main.getInstance().getDataConnection().getCollection().updateOne(foundDocument, updateOperation);
    }

}

相关问题