2

I have this code to Mongo in Golang

    cond := make([]bson.M, 0)
    cond = append(condiciones, bson.M{"$match": bson.M{"userId": ID}})
    cond = append(condiciones, bson.M{
        "$lookup": bson.M{
            "from":         "invoices",
            "localField":   "userId",
            "foreignField": "userId",
            "as":           "sales",
        }})
    cond = append(condiciones, bson.M{"$unwind": "$sales"})
    cond = append(condiciones, bson.M{"$skip": skip})
    cond = append(condiciones, bson.M{"$limit": 100})
    cond = append(condiciones, bson.M{"$sort": bson.M{"dateInvoice": -1}})

    cursor, err := collect.Aggregate(context.TODO(), cond)

I'm using Golang and MongoDB

"go.mongodb.org/mongo-driver/bson"

this works fine in union, limit and skipping documents, but the $sort doesn't work.. I have invoices but not ordered by 'dateInvoice'

I'm desperate.. please

What's wrong in my code ?

Regards

icza
  • 389,944
  • 63
  • 907
  • 827
Elba Nanero
  • 507
  • 1
  • 4
  • 10

2 Answers2

1

I have a solution.

Instead

cond = append(condiciones, bson.M{"$sort": bson.M{"dateInvoice": -1}})

Is necessary write

cond = append(condiciones, bson.M{"$sort": bson.M{"sales.dateInvoice": -1}})

Because the $sort, try to find the 'dateInvoice' in the initial collection 'users' and the dateInvoice field is in the sales collection.

Eklavya
  • 17,618
  • 4
  • 28
  • 57
Elba Nanero
  • 507
  • 1
  • 4
  • 10
0

You have to move the $sort before the $skip and $limit operations, else there is no guarantee the documents are listed in the same order when the query is repeated (optionally with different pagination parameters), which could result in "random" results. The $sort at the end only guarantees that the restricted max 100 documents will be sorted.

Sort first, so you get consistent behavior (given there are no invoices with the same dateInvoice timestamp).

icza
  • 389,944
  • 63
  • 907
  • 827