我们如何用Java编写这个MongoDB查询?

时间:2017-03-23 18:15:05

标签: java mongodb mongodb-java

 string result = "";
            string methodName = "GetCourse";                  
            string apiName = "core_course_get_courses";           
            string apiCall = moodleUrl + "?wstoken=" + token + "&wsfunction=" + apiName + "&moodlewsrestformat=json";

            try
            {
                using (WebClient client = new WebClient())
                {
                    client.BaseAddress = apiCall;
                    client.Headers[HttpRequestHeader.Accept] = "application/json";
                    result = client.DownloadString(apiCall);

1 个答案:

答案 0 :(得分:0)

Just"翻译"这进入org.bson.Document结构(类似于map)并调用正确的动作(它不是查询,在这种情况下它是一个聚合):

Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2003-01-01");
Document group = new Document();
group.put("_id", new Document("$year", "$Publication_Date"));
group.put("total", new Document("$sum", 1));
AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    new Document("$match", new Document("Publication_Date",
        new Document("$gte", date))),
    new Document("$group", group)
));

或使用com.mongodb.client.model包静态方法(更简洁):

AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    Aggregates.match(Filters.gte("Publication_Date", date)),
    Aggregates.group(
        new Document("$year", "$Publication_Date"),
        Accumulators.sum("total", 1))));