package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// Set up MongoDB client
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
// Access the desired collection
collection := client.Database("your_database_name").Collection("your_collection_name")
// Define the options for the find operation with sorting
findOptions := options.Find().SetSort(map[string]int{"field_name": 1})
// Perform the find operation with options
cursor, err := collection.Find(context.TODO(), bson.D{}, findOptions)
if err != nil {
log.Fatal(err)
}
// Iterate through the cursor and print the results
for cursor.Next(context.TODO()) {
var result bson.M
err := cursor.Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
// Close the cursor
cursor.Close(context.TODO())
// Close the MongoDB client
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
}