How to get values from a field in Mongo, using its Java Driver (3.5.0)

1k views Asked by At

I'm using MongoDB in javascript, and have been using Mongo's Java Driver. (It's because it is in JAR format and I'm using Mirth Connect). The thing is, I'm trying to use fields from another collection and bring informtation to the new collection. From what I've read, the filter from the Java Driver should return a DBCursor. I'm not good at javascript, and haven't figured out how to get a value from a field, from a query I made already.

I'm using this to make the query:

var uri = new Packages.com.mongodb.MongoClientURI("mongodb://usr:pwd@localhost:27017/admin");
var mongoClient = new Packages.com.mongodb.MongoClient(uri);
var database = mongoClient.getDatabase("mydb");
var collection = database.getCollection("mycollection");    
var person = collection.findOne(com.mongodb.client.model.Filters.eq("person.id", id));

For example, I would like to have the name of the person I associated with the ID. Any help of how can I get it, would be very appreciated.

Also the JSON from the collection is something like this:

{"patient" : {
                    "id": 1234,
                    "first_name": "Peter",
                    "last_name": "Parker",          
                },
 "other_stuff": ...
}
1

There are 1 answers

1
s7vr On BEST ANSWER

Try below code with find one ( find + first ) with dot notation to access first name for patient.

var uri = new Packages.com.mongodb.MongoClientURI("mongodb://usr:pwd@localhost:27017/admin");
var mongoClient = new Packages.com.mongodb.MongoClient(uri);
var database = mongoClient.getDatabase("mydb");
var collection = database.getCollection("mycollection");    
var personName = collection.find(com.mongodb.client.model.Filters.eq("person.‌​id", id)).first().get("patient.first_name")