【问题标题】:Find JSON value in mongodb java driver 3.0.x在 mongodb java driver 3.0.x 中查找 JSON 值
【发布时间】:2016-04-28 22:02:36
【问题描述】:

例如,我将这两个 JSON 文件插入到 mongo DB java 驱动程序 3.0.4 中。 我正在尝试根据字段 ID 获取详细信息。但我所有的努力都是徒劳的。谁能告诉我哪里搞砸了。提前致谢

Document {
    _id = 5721dd81ef31f82754eac196,
    Details = {
        "author_FirstName" : "Nishant",
        "author_LastName" : "Jayanth",
        "book_title" : "skjfsasfhkj",
        "Id" : 78,
        "publisher" : "tata",
        "year" : 1231,
        "ISBN" : 291939
    }

}

Document {
    _id = 5721dd81ef31f82754eac196,
    Details = {
        "author_FirstName" : "Nishant",
        "author_LastName" : "Jayanth",
        "book_title" : "skjfsasfhkj",
        "Id" : 777,
        "publisher" : "tata",
        "year" : 1231,
        "ISBN" : 291939
    }

}

这是我尝试根据 Id 检索的代码。

public String getAuthor(String id){
    String pId=String.valueOf(id);
    final String[] author = {null};
    FindIterable<Document> iterable=store.find(new Document("Id", 777)); //Probably this is where something is wrong
    iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) {
          author[0]=document.toString();
          System.out.println(document);
        }       
    });

        return author[0]; 
    }

尽我所知,我尝试了所有可能的组合。

new Document("Document.Details.Id":id);
new Document("Details.Id":id);
new Document("Document.Id":id);

但没有任何效果。

【问题讨论】:

  • 试试这个:文档["Details"]["Id"]
  • 您的 JSON 文档很奇怪。通常对于 Mongo,您应该删除外部“文档”并使其成为同名的集合。插入包含_idDetails的文档。

标签: java json mongodb


【解决方案1】:

上面的 JSON 文档没有被解析。解析文档并使用字段名称直接访问。

collection.insertOne(Document.parse(你的数据));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多