1

我有这个代码到 Golang 中的 Mongo

    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)

我正在使用 Golang 和 MongoDB

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

这在联合、限制和跳过文档中工作正常,但 $sort 不起作用.. 我有发票但没有按“dateInvoice”排序

我很绝望..拜托

我的代码有什么问题?

问候

4

2 回答 2

1

我有一个解决方案。

反而

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

有必要写

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

因为$sort,尝试在初始集合'users'中找到'dateInvoice',并且dateInvoice字段在sales集合中。

于 2020-04-19T22:40:56.327 回答
0

您必须在and操作$sort之前移动,否则无法保证在重复查询时文档以相同的顺序列出(可选地使用不同的分页参数),这可能会导致“随机”结果。最后只保证对限制的最多 100 个文档进行排序。$skip$limit$sort

首先排序,因此您可以获得一致的行为(假设没有具有相同dateInvoice时间戳的发票)。

于 2020-04-19T22:20:59.200 回答