Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove _id from mongodb result java

Tags:

java

mongodb

My code is

  DBCollection collection = db.getCollection("volume");
  DBCursor cursor = collection.find();
  DBObject resultElement = cursor.next();
  Map resultElementMap = resultElement.toMap();
  System.out.println(resultElementMap);

And the result is:

{_id=521b509d20954a0aff8d9b02, title={ "text" : "Volume Of Work Orders" , "x" : -20.0}, xAxis={ "title" : { "text" : "2012 "} , "categories" : [ "Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul" , "Aug" , "Sep" , "Oct" , "Nov" , "Dec"]}, yAxis={ "min" : 1000.0 , "max" : 7000.0 , "title" : { "text" : "Volume(K)"} , "plotLines" : [ { "label" : { "text" : "Average" , "x" : 25.0} , "color" : "black" , "width" : 2.0 , "value" : 30.0 , "dashStyle" : "solid"}]}, legend={ "backgroundColor" : "#FFFFFF" , "reversed" : true}, series=[ { "name" : "Volume" , "showInLegend" : false , "data" : [ 2909.0 , 3080.0 , 4851.0 , 3087.0 , 2960.0 , 2911.0 , 1900.0 , 3066.0 , 3029.0 , 5207.0 , 3056.0 , 3057.0]}]}

I need to remove _id from the result. I understand i need to play around with collection.find(), but please can anyone help me? Am not able to get sesired result

like image 405
user2572739 Avatar asked Aug 27 '13 02:08

user2572739


People also ask

How to remove_ id from MongoDB result in java?

You can remove the "_id" field from the map created: ... resultElementMap. remove("_id"); System.

How do you delete a record in MongoDB Java?

Using Java programCreate a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Get the object of the collection from which you want to delete the document, using the getCollection() method. Delete the required document invoking the deleteOne() method.

Can we change _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


1 Answers

Two options:

You can remove the "_id" field from the map created:

...
resultElementMap.remove("_id");
System.out.println(resultElementMap);

Or you can ask the query results to not include the _id field:

DBObject allQuery = new BasicDBObject();
DBObject removeIdProjection = new basicDBObject("_id", 0);

DBCollection collection = db.getCollection("volume");
DBCursor cursor = collection.find(allQuery, removeIdProjection);
DBObject resultElement = cursor.next();
Map resultElementMap = resultElement.toMap();
System.out.println(resultElementMap);

See the documentation on projections for all of the details.

like image 146
Rob Moore Avatar answered Oct 04 '22 15:10

Rob Moore