![](/img/trans.png)
[英]Update the specific field and not the whole document in MongoDB with Java
[英]Specific field of a document in MongoDb to Java Object
我想在 Mongodb 集合中选择文档的特定字段并将其转换为 java 对象。
我的文档是这样的:
{
"Name":"Ben",
"template":"A fingerprint template which I extracted"
}
所以我希望选择这个“模板字段”
我的示例代码如下:
List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>());
for (Document document : documents) {
Document doc = documents.get(document);
FingerprintTemplate template = (FingerprintTemplate) doc.get("template");
错误是:
java:不兼容的类型:org.bson.Document 无法转换为 int
请有任何想法或任何建议!!
您可以查询该字段是否存在:
collection.find("template": { $exists: true, $ne: null } });
对于映射部分,您可以查看 objectMapper 以直接映射到 java 对象: https ://www.baeldung.com/jackson-object-mapper-tutorial
您的错误仍然是您有一个 Document 而 Java 需要一个 int。
尝试这个 :
BasicDBObject query = new BasicDBObject();
BasicDBObject whereQuery = new BasicDBObject();
basicDBObject.put("template",1);
DBCursor cursor = collection.find(query,whereQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
这将打印具有template
的文档,但要转换为对象,您可能需要一些JSON Object mapper
可能是jackson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.