Inserting data into MongoDB with mgo

Change entry to:

type Entry struct {
    Id          string `json:"id" bson:"_id,omitempty"`
    ResourceId  int    `json:"resource_id" bson:"resource_id"`
    Word        string `json:"word" bson:"word"`
    Meaning     string `json:"meaning" bson:"meaning"`
    Example     string `json:"example" bson:"example"`
}

The syntax for Struct Tags does not use commas between tags. I believe this should fix it.


type Entry struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    ResourceId  int           `json:"resource_id" bson:"resource_id"`
    Word        string        `json:"word"`
    Meaning     string        `json:"meaning"`
    Example     string        `json:"example"`
}

Instead of Count() and Insert() you can use UpsertId which does just that, if an Id exists the record is replaced if not it's inserted.

Insert() with an empty ObjectId lets MongoDB handle Id assignment.

Edit: Misread your Count query. You also have an error in there. It should be "resource_id" not "resourceid" because you declared that the bson field is named "resource_id"

Tags:

Mongodb

Go

Mgo