Opsse Opsse - 6 months ago 33
Java Question

MongoDB aggregation with Java driver

I need your help for using MongoDB aggregation framework with java driver.
I don't understand how to write my request, even with this documentation.

I want to get the 200 oldest views from all items in my collection. Here is my mongo query (which works like I want in console mode):

db.items.aggregate(
{$unwind : "$views"},
{$match : {"views.isActive" : true}},
{$sort : {"views.date" : 1}},
{$limit : 200},
{$project : {"_id" : 0, "directKey" : "$views.directKey", "url" : "$views.url", "date" : "$views.date"}}
)


Items in this collection have one or many views.
My question is not about the request result, I want to know the java syntaxe.

Thank for your help, and sorry if I made english mistakes.

Answer

Finally found the solution, I don't know if it is the best one, but I get the same result than with my previous request.

    Iterable<DBObject> output = coll.aggregate(Arrays.asList(
            (DBObject) new BasicDBObject("$unwind", "$views"),
            (DBObject) new BasicDBObject("$match", new BasicDBObject("views.isActive", true)),
            (DBObject) new BasicDBObject("$sort", new BasicDBObject("views.date", 1)),
            (DBObject) new BasicDBObject("$limit", 200),
            (DBObject) new BasicDBObject("$project", new BasicDBObject("_id", 0).append("directKey", "$views.directKey")
                                                                                .append("url", "$views.url")
                                                                                .append("date", "$views.date"))
        )).results();

    for (DBObject dbObject : output)
    {
        System.out.println(dbObject);
    }

Thank to this link

Comments