Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb java driver 3.0 query

Tags:

java

mongodb

Hello i am working with mongodb java driver 3.0. i have a document like :

db.employee.find().pretty()

   "_id" : ObjectId("559e4ae4aed7561c94e565d5"),
   "empid" : 1,
   "name" : "abc",
   "dob" : "17/05/1990",
   "address" : [
           "559e4ae3aed7561c94e565d3",
           "559e4ae4aed7561c94e565d4"
   ]

I want to query on address fields and get all the addresses (in my case those values above) without specifying which value. My code is :

FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
        new Document("address", 559e4ae3aed7561c94e565d3));
iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) 
        System.out.println(document);
    }
});  

I don't want to specify the address manually. If I query on the address, I should get those two values. Any suggestions?

like image 455
Shaik Mujahid Ali Avatar asked Sep 21 '26 21:09

Shaik Mujahid Ali


1 Answers

Got the answer, we can query on the other known field for eg : empid and instead of returning whole document , only return the field which you require (in my case address).

FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
            new Document("empid", 1));
    iterable.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.get("address").toString());
        }
    });
like image 130
Shaik Mujahid Ali Avatar answered Sep 24 '26 09:09

Shaik Mujahid Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!