您好我正在尝试检索用户女巫的角色是基于另一个文档,我在用户文档中将此角色的参考作为对象列表
当这个被解雇时我犯了一个错误
List<Document> listRoles = (List<Document>) document.get("listRole");
com.mongodb.DBRef无法强制转换为org.bson.Document
{
"_id" : ObjectId("5a8bf269e1147736b4a7d06c"),
"_class" : "fr.anasys.testsecuritymongodb.models.User",
"username" : "hamou",
"password" : "amroun",
"actived" : true,
"listRole" : [
{
"$ref" : "role",
"$id" : ObjectId("5a8bf269e1147736b4a7d06a")
},
{
"$ref" : "role",
"$id" : ObjectId("5a8bf269e1147736b4a7d06b")
}
]
}
MongoDatabase database = mongoClient.getDatabase("rdproject2");
MongoCollection<Document> collection = database.getCollection("User");
Document document = collection.find(Filters.eq("username",email)).first();
if(document!=null) {
String username = document.getString("username");
String password = document.getString("password");
boolean actived = document.getBoolean("actived");
List<Document> listRoles = (List<Document>) document.get("listRole");
List<RefId> listRefIds = new ArrayList<>();
for (Document refId :listRoles ) {
listRefIds.add(new RefId(refId.getString("ref"),refId.getString("id" )));
}
答案 0 :(得分:0)
根据Resolve DBRef into Json,您可以将文档解码为JSON。
$ zip -r -X stuff.zip stuff/
updating: stuff/ (stored 0%)
updating: stuff/stuff1.txt (stored 0%)
updating: stuff/stuff2.txt (stored 0%)
$ shasum stuff.zip
1ed228b16d1ee803f26a8b1419f2eb3bf7fcb9f5 stuff.zip
$ zip -r -X stuff.zip stuff/
updating: stuff/ (stored 0%)
updating: stuff/stuff1.txt (stored 0%)
updating: stuff/stuff2.txt (stored 0%)
$ shasum stuff.zip
1ed228b16d1ee803f26a8b1419f2eb3bf7fcb9f5 stuff.zip
然后您可以从JSON解析以获取id字段。这可能不是解决问题的最佳方法,但这就是我现在正在做的事情。