我的mongodb中有80,000个文件。我正在使用Java驱动程序查询这些文档。我尝试根据特定字段对文档进行排序,然后对此结果应用不同的过滤器。排序选项工作正常,但我无法获得不同的文档。我附上了我的工作实例。
Document query = new Document("RetweetCount",-1);
MongoCursor<Document> cursor = collection.find().sort(query).iterator();
try{
while(cursor.hasNext()) {
Document dr = (Document) cursor.next();
String stat = dr.getString("status");
int retweetcount = dr.getInteger("RetweetCount");
//Sort works fine. I have to apply distinct here!!! distinct is based on status field
System.out.println(retweetcount+"--->"+stat);
}
}finally{
cursor.close();
}
}
答案 0 :(得分:0)
我尝试了这种方法,但却提取了一些不相关的字段。I referred this link
ArrayList<Document> dd = new ArrayList<Document>();
//MongoCursor<Document> cursor1 = collection.find().sort(query).iterator();
Document grouping = new Document("_id","$status");
grouping.append("text", new Document("$first","$_id"));
grouping.append("RetweetCount", new Document("$first","$RetweetCount"));
grouping.append("screen_name", new Document("$first","screen_name") );
Document group = new Document("$group",grouping);
System.out.println(group);
Document sortfields = new Document("RetweetCount",-1);
Document sort = new Document("$sort",sortfields);
Document projectfields = new Document("_id",0);
projectfields.append("_id", "$text");
projectfields.append("RetweetCount", "$RetweetCount");
projectfields.append("sn", "$screen_name");
Document projects = new Document("$project",projectfields);
AggregateIterable<Document> iterable = collection.aggregate(asList(new Document(group),new Document(sort),new Document(projects)));
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
});
输出:
{ "_id" : { "$oid" : "576124fafbfb870794452ac6" }, "RetweetCount" : 643, "sn" : "screen_name" }
它省略了我的文本字段,而是返回id字段。我转发的订单也不正确。 此方法工作正常,但结果不同。 谁能请你纠正我!!!