对字段中是否存在值进行排序



我有一个Student结构体,看起来像这样。

type Student struct {
Name            string                         `json:"name" bson:"name"`
Marks           int                            `json:"marks" bson:"marks"`
Subjects        []string                       `json:"subjects" bson:"subjects"`
}

我使用opts.Sort对结果进行排序。更多关于

opts.Sort = bson.D{
{Key: "marks", Value: -1},
}

我还想按Subjects排序结果,在某种程度上,如果对于任何学生,如果主题Math存在,它应该在顶部排序(降序),然后按marks排序我试着做这个

opts.Sort = bson.D{
{Key: "subjects", Value: bson.M{"$in": "math"}},
{Key: "marks", Value: -1},
}

我知道这似乎不对,因为我没有传递1或-1,但我不知道如何修改它使其工作。我错过了什么?

单用一个"simple"查询。

查询按marks排序的记录,并在Go中进行第二次排序,通过将具有"math"的文档移动到前面。

如果你只需要在MongoDB中这样做,你可以重新设计:例如,你可以在文档中添加一个布尔字段来存储学生是否有"math"的信息,所以你可以很容易地将其包含在排序中。

请注意,您可以在Aggregation框架中这样做。这是您需要的查询:

db.students.aggregate(
{$addFields:{"hasMath": {$in:["math", "$subjects"]}}},
{$sort:{hasMath: -1, marks: -1}}
)

这所做的基本上是我建议的:它添加了一个hasMath字段,告诉学生在subjects数组中是否有"math",然后首先按hasMath降序排序文档,然后按标记降序排序。

这是你在Go中使用官方mongo-go驱动程序的方法:

c := ... // Obtain students collection
pipe := []bson.M{
{"$addFields": bson.M{
"hasMath": bson.M{"$in": []any{"math", "$subjects"}},
}},
{"$sort": bson.D{
{Key: "hasMath", Value: -1},
{Key: "marks", Value: -1},
}},
}
curs, err := c.Aggregate(ctx, pipe)
if err != nil {
// Handle error
panic(err)
}
var students []Student
if err := curs.All(ctx, &students); err != nil {
// Handle error
panic(err)
}

相关内容

最新更新