簡體   English   中英

使用 Java 驅動程序對 MongoDB 聚合查找階段的結果進行排序

[英]Sort the result of the MongoDB aggregation lookup stage using Java driver

我試圖讓 Mongo 返回一個客戶的訂單列表。 訂單是使用$lookup添加到客戶文檔的列表(數組)。

我有這個主要工作我無法正確排序訂單的查找集合。 除了排序之外,它可以分開工作。

我想我可能需要使用$unwind但我發現很難知道如何將它集成到查找中以及需要放置在哪里。

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")));

我確實查看了谷歌和堆棧溢出,但找不到看起來解決了我遇到的問題的答案。

我想按加入客戶的訂單集合中的date_raised對訂單進行排序。

我不太確定您的數據 model 是怎樣的。 另一方面,這個怎么樣?

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)
                )
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM