0

I am quit new to MongoDB. I have a collection with few documents inside. Below is a example for that.

 {"UserID": "1", "Name": "John", "Marks":40} 
 {"UserID": "2", "Name": "Mark", "Marks":50} 
 {"UserID": "3", "Name": "Jesse", "Marks":60} 

I want to get the marks of all the entries to an array to display them and to do some calculations using java. so far I have done the blow to read the document and display all the data. But I couldn't find a way to get only the "Marks" out of it.

 MongoClient client = new MongoClient("localhost",27017); 
 DB db = client.getDB( "test_db" );
 DBCollection collection = db.getCollection("AllocatedMarks");

 DBCursor cursor = collection.find();
 while(cursor.hasNext()) {
    System.out.println(cursor.next());
 }

This all I know about reading data from MongoDB using Java so far. Please help me to get only the marks field from the document to an array.
Thank you.

Himanshu Bhandari
  • 1,769
  • 2
  • 23
  • 37
jayz
  • 401
  • 1
  • 5
  • 25

3 Answers3

2

You just need to pass key to the get() method, so you can do this way:

for(int i=0; i<cursor.size();i++){
   System.out.println(cursor.get(i).get("Marks"));
}

Similarly using foreach loop you can do...

Thanks.

Himanshu Bhandari
  • 1,769
  • 2
  • 23
  • 37
2

Here is how to get the "Marks":

DBObject dbObject;
while(cursor.hasNext()) {
   dbObject = cursor.next();
   int marks = ((Number)dbObject.get("Marks")).intValue()
}

You may be able to cast directly to an Integer instead of a Number.

Not important, but if you wanted to only load the "Marks" you could issue your query as so:

BasicDBObject fieldsDBObject = new BasicDBObject();
fieldsDBObject.append("Marks",true);
DBCursor cursor = collection.find(null, fieldsDBObject);
markwatsonatx
  • 3,391
  • 2
  • 21
  • 19
1

Well you can use the get() method in DBCursor object.
Use it as

System.out.println(cursor.next().get("Marks");

Refer MongoDB api for details.
DBCursor , DBObject , BSONObject

Isuru Pathirana
  • 1,060
  • 1
  • 16
  • 37