Remove _id from mongodb result java

My code

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

And the result:

{_ id = 521b509d20954a0aff8d9b02, title = {"text": "Workload 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" , "reverseed": 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 with collection.find (), but please, can someone help me? I can not get the result sesired

+5
source share
2 answers

Two options:

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

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

Or you can query the results of the query so that they do 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 projections documentation for more information.

+6
source

Another option to consider if you are reading the results iteratively is to do something like this:

 final FindIterable<Document> foundResults = collection.find(); for (final Document doc : foundResults) { doc.remove("_id"); // doc.toJson() no longer has _id } 
0
source

Source: https://habr.com/ru/post/1499052/


All Articles