Sort on look up in mongo using java

I want to sort the array return by lookup in mongo then use projection on that data in java. Can someone suggest how to do that.

Sample code:

Mongoclient.getDatabase(db).get collection(order request).aggregate(Arrays.asList(new Document("$lookup",new Document( "from", "order").append("localfield","Id").append("foreignField","Id").append("as", "orders")),
new Document("$lookup",new Document( "from", "Inventory").append("localfield","Id").append("foreignField","Id").append("as", "inventory")),
new Document("$project", new Document ("I'd",0L).append("order date", new Document("$arrayElementAt", Arrays.asList("$orders.date",0L)))

I want to have max order date return by lookup on orders

Hi @Sameer_kr and welcome to MongoDB community forums!!

Based on the above requirement and the sample data examples in the $lookup documentation, I tried to create the following aggregation pipeline to sort the data based on “instock” field in descending order and the use $limit to display the max instock document.

Aggregation Pipeline:

[
  {
    $lookup:
      {
        from: "inventory",
        localField: "item",
        foreignField: "sku",
        as: "inventory_docs",
      },
  },
  {
    $sort:
      {
        "inventory_docs.instock": -1,
      },
  },
  {
    $limit:
      1,
  },
]

and the resultant Java code:

Arrays.asList(new Document("$lookup", 
    new Document("from", "inventory")
            .append("localField", "item")
            .append("foreignField", "sku")
            .append("as", "inventory_docs")), 
    new Document("$sort", 
    new Document("inventory_docs.instock", -1L)), 
    new Document("$limit", 1L))

If the above is not what you are looking for, could you help me with the sample document and the desired output from the aggregation pipeline.

Also, MongoDB Atlas and Compass provides you the functionality to export the aggregation pipeline stages into the desired driver code. Please visit the documentation for more information.

Regards
Aasawari