I'm using find one to find a specific user_id and return an array data which is in the specific document.
Below is my document structure
package main
import (
"context" // manage multiple requests
"fmt" // Println() function
"os"
"reflect" // get an object type
// import 'mongo-driver' package libraries
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Fields struct {
user_id string
data struct {
year string
day string
revenue int
}
max int
}
func main() {
// Declare host and port options to pass to the Connect() method
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to the MongoDB and return Client instance
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
fmt.Println("mongo.Connect() ERROR:", err)
os.Exit(1)
}
// Declare Context type object for managing multiple API requests
// Access a MongoDB collection through a database
col := client.Database("graph").Collection("alltime")
fmt.Println("Collection type:", reflect.TypeOf(col), "\n")
// Declare an empty array to store documents returned
var result Fields
// Get a MongoDB document using the FindOne() method
err = col.FindOne(context.TODO(), bson.D{{"user_id", "11664"}}).Decode(&result)
if err != nil {
fmt.Println("FindOne() ERROR:", err)
os.Exit(1)
} else {
// fmt.Println("FindOne() result:", result)
fmt.Println("FindOne() Name:", result.data)
// fmt.Println("FindOne() Dept:", result.Dept)
}
}
But this is the output i'm getting
varun@Varuns-MacBook-Air sql-test % go run mongofind.go
Collection type: *mongo.Collection
FindOne() Name: { 0}
