duanlan7903 2019-04-25 22:53
浏览 40
已采纳

使用结构切片更新文档

Trying to update a document in MongoDB using the official mongo driver,go.mongodb.org/mongo-driver/mongo

this is my struct that I want to update

type Activity struct {
    Timestamp    time.Time          `bson:"timestamp,omitempty"`
    Type         string             `bson:"type,omitempty"`
}

type Member struct {
    ID           primitive.ObjectID `bson:"_id,omitempty"`
    Name         string             `bson:"name,omitempty"`
    Activities []Activity           `bson:"activities ,omitempty"`
}

this is the code for updating document

filter := bson.M{"_id": m.ID}
update := bson.M{
    "$set": bson.M{
        "name":        m.Name,
    },
    "$each": bson.M{"activities": m.Activities },
}

res, err := coll.UpdateOne(ctx, filter, update)

the name gets updated but nothing happens with the activities

what am I doing wrong? should I use ReplaceOne instead?

  • 写回答

1条回答 默认 最新

  • douchao0358 2019-04-26 00:55
    关注

    the name gets updated but nothing happens with the activities

    This is because $each array update operator is designed to be used with $addToSet (append unique) or $push(append).

    For example, if you would like to update the array with no duplicate activities the set:

    update := bson.M{
        "$set": bson.M{
            "name": obj.Name,
        },
        "$addToSet": bson.M{"activities": bson.M{"$each": obj.Activities }},
    }
    cursor, err := collection.UpdateOne(context.Background(), filter, update )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度