0

In general FindOne fmt.print result { }. I need to output Value.

I'm using pretty much standard setup from documentation: https://docs.mongodb.com/ecosystem/drivers/go/

I have problems with creating query because most of examples are different; I've tried to follow this pattern: https://github.com/ruanbekker/code-examples/blob/master/mongodb/golang/examples.go

Reference object:

_id:5d1a8829cf5042c071458db6
name:" !hello"
Value:" World %c end"
Counter:0 

Code examples:

type userModel struct {
    Uname string
    Url   string
}

var result userModel
filter := bson.D{{"name", " !hello"}}
db := Client.Database("Nothing").Collection("databaseC")
db.FindOne(context.Background(), filter).Decode(&result)
fmt.Println(result)
fmt.Println(result.Url)

// Output { 0} // Output empty

type userModel struct {
    Name    string
    Value   string
    Counter int
}
var result userModel
findOneOptions := options.FindOne()
findOneOptions.SetProjection(bson.D{{"name", "!new"}})

filter := bson.D{{}}
db := Client.Database("Nothing").Collection("databaseC")
db.FindOne(context.TODO(), filter, findOneOptions).Decode(&result)
fmt.Println(result)

// Output nothing

// different collection with simple struct

type userModel struct {
    Uname string
    Url   string
}
var result userModel
filter := bson.D{{"name", "object"}}
db := Client.Database("Nothing").Collection("Video")
db.FindOne(context.Background(), filter).Decode(&result)
fmt.Println(result)
fmt.Println(result.Url)

// Output { } // Output empty

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dinamis
  • 1
  • 1
  • What happens if you use `bson.M` as the filter? `filter := bson.M{"name", " !hello"}` – icza Jul 02 '19 at 12:16
  • 1
    Also use `bson` [struct tags](https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373) to map between struct fields and fields of your MongoDB documents. – icza Jul 02 '19 at 12:18
  • @icza hey, i belive `bson.M{"name", " !hello"}` - will contain cmpile error, missing type in composite literal. but i was tryed: `filter := bson.M{"name": " !hello"}` and it's have the same result. { 0} – Dinamis Jul 02 '19 at 12:24

1 Answers1

0
type userModel struct {
    name    string `bson:"name"`
    Value   string `bson:"Value"`
    Counter int    `bson:"Counter"`
}
var result userModel
filter := bson.M{"name": " !hello"}
db := Client.Database("Nothing").Collection("databaseC")
db.FindOne(context.Background(), filter).Decode(&result)
fmt.Println(result)
fmt.Println(result.Value)

Outputs an actual value. Thanks @icza

Dinamis
  • 1
  • 1