-1

I'm new to mongoDB and have set up a java application to communicate with my db. I only have one collection in my db that contains several documents. Is there a way that I can make a single query to grab my collection and then somehow access all the fields in each document?

I attempted to create a query and then add all my DBObjects to an ArrayList. But once I've done that, I can't figure out how I can access the data in each document.

Here's what I have so far:

ArrayList<DBObject> docs = new ArrayList<DBObject>();
DBCollection coll = db.getCollection("testCollection");

DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
   docs.add(cursor.next());
}
} finally {
   cursor.close();
}

//how do I access everything in my docs???
docs.get(0).find("id", 1);
DanielD
  • 1,315
  • 4
  • 17
  • 25

2 Answers2

0

Yes you can access all the values from docs. Iterate over docs like below

for(DBObject obj: docs){
    obj.get("_id");
}
Indrajeet
  • 642
  • 1
  • 6
  • 12
0

Since each object in your list is a DBObject you should be able to access field values with something like this:

BasicDBObject doc = docs.get(0);
String fieldValue = doc.getString("nameOfField");

You can't do a find("id", 1) like you are doing on your array list but you can do it on your DBCollection "coll". The format will be a little different, something like coll.find({ id: 1}). Then you will get a collection of the results. If you are looking for just a single record, then use coll.findOne() like this.

You will have to iterate through your array list another way to do your own searching. I recommend creating a class containing properties to match the fields each document. Here is another resource that may help:

converting-dbobject-to-java-object-while-retrieve-values-from-mongodb

I also recommend this tutorial link if you haven't already seen it.

Community
  • 1
  • 1
jzapata
  • 1,229
  • 1
  • 12
  • 17