5

我的代码是

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

结果是:

{_id=521b509d20954a0aff8d9b02,title={“text”:“工单数量”,“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]}]}

我需要从结果中删除 _id。我知道我需要使用collection.find(),但是有人可以帮助我吗?我无法获得成功的结果

4

2 回答 2

6

两种选择:

您可以从创建的地图中删除“_id”字段:

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

或者您可以要求查询结果不包含 _id 字段:

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);

有关所有详细信息,请参阅有关投影的文档。

于 2013-08-27T02:35:02.977 回答
0

如果您正在迭代地阅读结果,另一个要考虑的选择是执行以下操作:

final FindIterable<Document> foundResults = collection.find();
for (final Document doc : foundResults) {
    doc.remove("_id");
    // doc.toJson() no longer has _id
}
于 2019-05-05T09:16:23.707 回答