使用Java驱动程序对MongoDB聚合查找阶段的结果进行排序

我正在尝试让Mongo返回客户的订单列表。其中 orders 是使用$lookup添加到 customer 文档的列表(数组)。

我主要在此工作,但我无法正确获取订单的查找集合。除了排序,它可以分开工作。

我认为我可能需要使用$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")));

我确实查看了google和堆栈溢出,但找不到看起来像它解决了我所遇到问题的答案。

我想按加入客户的订单集合中的date_raised对订单进行排序。

pk110987 回答:使用Java驱动程序对MongoDB聚合查找阶段的结果进行排序

我不太确定您的数据模型如何。另一方面,如何呢?

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)
                )
);
本文链接:https://www.f2er.com/2377530.html

大家都在问