1

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

Collection

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}

2
  • Your struct fields are not exported. Capitalize the field names and use bson tags. Commented Jan 24, 2020 at 6:04
  • Hey didn't quite get you, can you show an example Commented Jan 24, 2020 at 6:09

1 Answer 1

2

The driver needs to set the fields using reflection, and for the reflection to work, the struct fields must be exported. When you export them, the names no longer match the database names, so you have to add bson tags. Also, your Data field is not an array in the struct:

type Fields struct {
    User_id string `bson:"user_id"`
    Data  []struct {
        Year string `bson:"year"`
        Day string `bson:"day"`
        Revenue int `bson:"revenue"`
    } `bson:"data"`
    Max int `bson:"max"`
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.