gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:41:14 26 4
gpt4 key购买 nike

我正在尝试让 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 对订单进行排序。

最佳答案

我不太确定您的数据模型如何。另一方面,这个怎么样?

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

关于java - 使用 Java 驱动程序对 MongoDB 聚合查找阶段的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com