【问题标题】:How can I update and specific nested struct field in MongoDB with golang using bson如何使用 bson 使用 golang 更新 MongoDB 中的特定嵌套结构字段
【发布时间】:2020-09-09 17:07:05
【问题描述】:

这就是我想要实现的目标:

bson.M{constants.MONGO_SET: entity.UserShop{Shop.ID: userShop.Shop.ID}}

改为使用

bson.M{constants.MONGO_SET: entity.UserShop{"shop._id": userShop.Shop.ID}}

存在

type UserShop struct {
  User `json:"-"  bson:"-"`
  Shop `json:"shop,omitempty"  bson:"shop,omitempty"`
}

购物

type Shop struct {
    ID          primitive.ObjectID `json:"-" bson:"_id,omitempty"`
    Name        string             `json:"name,omitempty" bson:"name,omitempty"`
    Description string             `json:"description,omitempty" bson:"description,omitempty"`
    ImageURL    string             `json:"imageURL,omitempty" bson:"imageURL,omitempty"`
    Stars       int64              `json:"stars,omitempty" bson:"stars,omitempty"`
    // Location    *[]int64           `json:"location,omitempty" bson:"location,omitmepty"`
    // Products    *AllProducts       `json:"products,omitempty" bson:"products,omitempty"`
}

在数据库结构中:

商店:{ _id:“12344”, 名称:“你好” }

我想修改任何特定字段,并且不修改 shop 对象内的任何其他字段

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    使用以下表达式仅更新 shop._id 字段:

    bson.M{"$set":bson.M{"shop._id":userShop.Shop.ID}}
    

    【讨论】:

    • 我只是想避免使用“shop._id”字符串,想知道是否有一种方法可以使用给定的结构来实现相同的行为。
    • 给定的结构有一个 int64 字段,该字段将始终添加到表达式中。如果需要,您可以定义一个仅包含 _id 字段的单独结构。
    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2019-06-20
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多