Search code examples
javamongodbjoinmongodb-java

Sort the result of the MongoDB aggregation lookup stage using Java driver


I am trying to get Mongo to return a list of orders for a customer. Where the orders are a list (array) added to the customer document by use of $lookup.

I have this mostly working i'm having trouble getting the lookup collection of orders sorting correctly. It works apart except the sort.

I think I might need to use a $unwind but i'm finding it difficult to know how to integrate that in a lookup and where it needs to be placed.

List<Bson> pipeline
        = Arrays.asList(
            new Document("$match", new Document("_id", new ObjectId(customerId))),
            new Document("$lookup",
                    new Document("from", "orders")
                            .append("localField", "_id")
                            .append("foreignField", "customer_id")
                            .append("as", "orders")));

I did take a look on google and stack overflow but couldn't find an answer that looked like it solved the issue I have.

I would like to sort the orders by the date_raised that is in the orders collection im joining to the customers.


Solution

  • I'm not quite sure how your data model is. On the other hand, how about this?

    List<Bson> pipeline
            = Arrays.asList(
            new Document()
                    .append("$match", new Document()
                            .append("_id", new Document("_id", new ObjectId(customerId)))
                    ),
            new Document("$lookup",
                        new Document("from", "orders")
                                .append("localField", "_id")
                                .append("foreignField", "customer_id")
                                .append("as", "orders")));
            new Document()
                    .append("$unwind", new Document()
                            .append("path", "$date_raised")
                    ), 
            new Document()
                    .append("$sort", new Document()
                            .append("date_raised", 1.0)
                    )
    );