【发布时间】:2015-07-06 06:52:04
【问题描述】:
我在 mongodb 中执行一个查询,结果如下:
{
"_id" : "180",
"total" : 1
},
{
"_id" : "181",
"total" : 1
},
{
"_id" : "182",
"total" : 29
}
这里我通过 _id 的上限为 186,下限为 180。
因此,查询搜索 _id 并传递该值。
但我想按如下方式存储结果。缺少的 _id 应该存储 0。
{
"_id" : "180",
"total" : 1
},
{
"_id" : "181",
"total" : 1
},
{
"_id" : "182",
"total" : 29
},
{
"_id" : "183",
"total" : 0
},
{
"_id" : "184",
"total" : 0
},
{
"_id" : "185",
"total" : 0
},
{
"_id" : "186",
"total" : 0
}
我正在尝试通过以下方式在 Java 中获取结果后插入值。
dayST 和 daySTP 是 _id 的上限和下限。
output = table.aggregate( pipeline );
for ( final DBObject res : output.results() )
{
for (;dayST<daySTP;dayST++)
{
int _id1 = Integer.parseInt(res.get("_id").toString());
if(dayST == _id1)
{
data.add( new Gson().fromJson( res.toString(), JsonObject.class ) );
}
else
{
final JsonObject dataForNoResults = new JsonObject();
dataForNoResults.addProperty( "_id", dayST );
dataForNoResults.addProperty( "totalcount", 0 );
data.add( dataForNoResults );
}
}
}
但是,它给出以下输出:
{"_id":"180","totalcount":1},
{"_id":181,"totalcount":0},
{"_id":182,"totalcount":0},
{"_id":183,"totalcount":0},
{"_id":184,"totalcount":0},
{"_id":185,"totalcount":0},
{"_id":186,"totalcount":0}
我知道我的循环中的逻辑不正确。有人可以指出吗?
编辑: 我用这个解决了它:
ArrayList<Integer> ar = new ArrayList<Integer>();
ArrayList<Integer> br = new ArrayList<Integer>();
output = table.aggregate( pipeline );
for ( final DBObject res : output.results() )
{
data.add( new Gson().fromJson( res.toString(), JsonObject.class ) );
ar.add(Integer.parseInt(res.get("_id").toString()));
}
while(dayST<daySTP)
{
if(!ar.contains(dayST)){
br.add(dayST);}
dayST++;
}
for(int i = 0;i< br.size();i++)
{
final JsonObject dataForNoResults = new JsonObject();
dataForNoResults.addProperty( "_id", br.get(i) );
dataForNoResults.addProperty( "totalcount", 0 );
data.add( dataForNoResults );
}
有没有更好的解决方案?
【问题讨论】:
标签: java json mongodb mongodb-query mongodb-java