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.
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)
)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.