MongoDB aggregation with Java driver

后端 未结 4 1219
北恋
北恋 2020-11-29 04:34

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 t

4条回答
  •  Happy的楠姐
    2020-11-29 05:29

    Finally found the solution, I get the same result than with the original request.

    Mongo Driver 3 :

    Aggregate doc

    MongoCollection collection = database.getCollection("myCollection");
    
    AggregateIterable output = collection.aggregate(Arrays.asList(
            new Document("$unwind", "$views"),
            new Document("$match", new Document("views.isActive", true)),
            new Document("$sort", new Document("views.date", 1)),
            new Document("$limit", 200),
            new Document("$project", new Document("_id", 0)
                        .append("url", "$views.url")
                        .append("date", "$views.date"))
            ));
    
    // Print for demo
    for (Document dbObject : output)
    {
        System.out.println(dbObject);
    }
    

    You can make it more readable with static import :
    import static com.mongodb.client.model.Aggregates.*;.
    See koulini answer for complet example.

    Mongo Driver 2 :

    Aggregate doc

    Iterable output = collection.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("url", "$views.url")
                        .append("date", "$views.date"))
            )).results();
        
    // Print for demo
    for (DBObject dbObject : output)
    {
        System.out.println(dbObject);
    }
    

    Query conversion logic : Thank to this link

提交回复
热议问题