go mongo 查询一条 排序

 

 

 

func ExampleCollection_FindOne() {
    var coll *mongo.Collection
    var id primitive.ObjectID

    // Find the document for which the _id field matches id.
    // Specify the Sort option to sort the documents by age.
    // The first document in the sorted order will be returned.
    opts := options.FindOne().SetSort(bson.D{{"age", 1}})
    var result bson.M
    err := coll.FindOne(
        context.TODO(),
        bson.D{{"_id", id}},
        opts,
    ).Decode(&result)
    if err != nil {
        // ErrNoDocuments means that the filter did not match any documents in
        // the collection.
        if err == mongo.ErrNoDocuments {
            return
        }
        log.Fatal(err)
    }
    fmt.Printf("found document %v", result)
}

 

posted @ 2022-10-26 15:43  AngDH  阅读(16)  评论(0编辑  收藏  举报