简体   繁体   中英

How use update function of mongo-go-driver using struct

The update function of mongo-go-driver can be called like this.

filter := bson.D{"username", username}
update := bson.D{{"$set",
    bson.D{
        {"name", person.Name},
    },
}}
result, err := collection.UpdateOne(ctx, filter, update)
type Person struct {
    ID       primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string             `json:"username,omitempty" bson:"username,omitempty"`
    Name     string             `json:"name,omitempty" bson:"name,omitempty"`
}

But, I need to call the update function using the person struct, without mentioning every field of person struct like this.

filter := bson.D{"username", username}
update := bson.D{{"$set", <<how to convert person struct to bson document?>>}}
result, err := collection.UpdateOne(ctx, filter, update)

How can I convert the person struct to bson document?

ReplaceOne I think is what you're after:

        // Use it's ID to replace
        filter := bson.M{"_id": existing.ID}
        // Create a replacement object using the existing object
        replacementObj := existing
        replacementObj.SomeFieldToChange = "new-replacement-object"
        updateResult, err := coll.ReplaceOne(context.Background(), filter, replacementObj)
        assertNotErr(t, err)
        assertEquals(t, 1, int(updateResult.ModifiedCount))

A note that ErrNotFound is no longer thrown as it was in mgo - you have to check the Modified/Upserted count.

You could do something like this:

func Update(person Person) error {
  pByte, err := bson.Marshal(person)
  if err != nil {
    return err
  }

  var update bson.M
  err = bson.Unmarshal(pByte, &update)
  if err != nil {
    return
  }

  // NOTE: filter and ctx(Context) should be already defined
  _, err = collection.UpdateOne(ctx, filter, bson.D{{Key: "$set", Value: update}})
  if err != nil {
    return err
  }
  return nil
}

how about marshalling the person struct to bson?

package main

import (
        "fmt"

        "labix.org/v2/mgo/bson"
)

type person struct {
        ID       string `json:"_id,omitempty" bson:"_id,omitempty"`
        Username string `json:"username,omitempty" bson:"username,omitempty"`
        Name     string `json:"name,omitempty" bson:"name,omitempty"`
}

func main() {
        p := person{
                ID:       "id",
                Username: "uname",
                Name:     "name",
        }
        var (
                bm  []byte
                err error
        )
        if bm, err = bson.Marshal(p); err != nil {
                panic(fmt.Errorf("can't marshal:%s", err))
        }
        update := bson.D{{"$set", bm}}
        fmt.Printf("update is:%q\n", update)
}

run:

 ./sobson
update is:[{"$set" "4\x00\x00\x00\x02_id\x00\x03\x00\x00\x00id\x00\x02username\x00\x06\x00\x00\x00uname\x00\x02name\x00\x05\x00\x00\x00name\x00\x00"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM