简体   繁体   中英

How do I query document like this in Java Driver for MongoDb?

I have a document like this.

"item" : "060478132",
    "some_id" : {
        "5" : {
            "obj1" : "4",
            "obj2" : "4"
        }
    }

This is what I'm doing right now which I think it could be better but I'm new in Java Driver for mongo

DBObject query = start("item").is("060478132").get();
DBObject obj = collection.find(query).toArray().get(0);
DBObject some_ids = (DBObject) obj.get("some_id");
DBObject theObj = (DBObject) some_ids.get("5");

MongoDB allows projection based on fields, so you can reduce the number of fields in the resulting document. But you cannot directly query sub-documents. What I also saw in your code is the way how the query object is constructed. Use a simple new BasicDBObject(...) instead!

Full example with null checks:

DBObject query = new BasicDBObject("item", "060478132");
DBObject document = collection.findOne(query, new BasicDBObject("some_id", 1);
if (document != null) {
    DBObject someId = document.get("some_id");
    if (someId != null) {
        DBObject result = someId.get("5");
    }
}

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