Home  >  Article  >  Backend Development  >  Golang and MongoDB - I tried to update toggle boolean to mongodb using golang but got the object

Golang and MongoDB - I tried to update toggle boolean to mongodb using golang but got the object

WBOY
WBOYforward
2024-02-14 22:40:151000browse

Golang 和 MongoDB - 我尝试使用 golang 将切换布尔值更新为 mongodb,但得到了对象

Question content

I have used React and Nodejs to implement a todo application. The switching function for updating the Mongodb database in React and Nodejs is as follows:

const toggleChecked = ({ _id, isChecked }) => {
  TasksCollection.update(_id, {
    $set: {
      isChecked: !isChecked
    }
  })
};

I want to implement toggle function in Golang to update boolean field, but I got the object, the following is the golang code:

func updateOneMovie(movieId string) model.Netflix {
    id, _ := primitive.ObjectIDFromHex(movieId)
    filter := bson.M{"_id": id}
    update := bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
    var updateResult model.Netflix

    result, err := collection.UpdateOne(context.Background(), filter, update)

    err = collection.FindOne(context.Background(), filter).Decode(&updateResult)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result)
    return updateResult
}

Results in Mongodb are updated as objects instead of booleans. How can I fix it so that it updates the toggle boolean?

Workaround

Pass a single document (e.g. bson.M or bson.D) as the update document and the field names and values ​​will be as-is ( Literal meaning) explanation.

Using the aggregation pipeline with updates a>, you must pass an array as the update document, which triggers its interpretation as an aggregation pipeline. This is the only requirement. The array may be mongo.Pipeline, bson.A, []bson.D, [ ]bson.M or even []any, it doesn't matter, it must be an array or a slice in Go. These elements can be bson.M, bson.D, or any other value representing the document.

Easiest solution:

filter := bson.M{"_id": id}
update := []any{
    bson.M{"$set": bson.M{"watched": bson.M{"$not": "$watched"}}}
}

The above is the detailed content of Golang and MongoDB - I tried to update toggle boolean to mongodb using golang but got the object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete