简体   繁体   中英

Find JSON value in mongodb java driver 3.0.x

For instance I am having these two JSON files which I inserted in to mongo DB java driver 3.0.4. I am trying to fetch details based on the field Id. But all my efforts are under vain. Can anyone tell where I messed up. Thanks in Advance

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
    }

}

This is my code where I am trying to retrieve based on 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]; 
    }

I tried all the possible combinations to the best of my knowledge.

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

But nothing worked.

The above JSON doc is not parsed . Parse the document and straight away access with field name.

collection.insertOne(Document.parse(your data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM