douchen4915 2018-04-03 13:08
浏览 38
已采纳

如何返回ID为的嵌入式文档

I have a MongoDB collection with an example document like this:

Mongo example document

What I want to do (as you can see from the actual code) is to update a role field in members.x.role where members.x.id equals given ID (ID is UUID so it's unique; this part of code works without problem) and then I want to return that members.x. But the problem is that it always returns first member instead of the one that has been just updated. I've tried some methods of mgo and found Distinct() be closest to my expectations, but that doesn't work as I want.

My question is how can I return member embedded document with specified ID?

I've already looked on this and this but it didn't help me.

func (r MongoRepository) UpdateMemberRole(id string, role int8) (*Member, error) {
    memberQuery := &bson.M{"members": &bson.M{"$elemMatch": &bson.M{"id": id}}}
    change := &bson.M{"members.$.role": role}

    err := r.db.C("groups").Update(memberQuery, &bson.M{"$set": &change})
    if err == mgo.ErrNotFound {
        return nil, fmt.Errorf("member with ID '%s' does not exist", id)
    }

    // FIXME: Retrieve this member from query below. THIS ALWAYS RETURNS FIRST MEMBER!!!
    var member []Member
    r.db.C("groups").Find(&bson.M{"members.id": id}).Distinct("members.0", &member)

    return &member[0], nil
}
  • 写回答

1条回答 默认 最新

  • dongyaofu0599 2018-04-03 13:56
    关注

    I found a workaround, it's not stricte Mongo query that is returning this embedded document, but this code is IMO more clear and understandable than some fancy Mongo query that fetches whole document anyway.

    func (r MongoRepository) UpdateMemberRole(id string, role int8) (*Member, error) {
        change := mgo.Change{
            Update: bson.M{"$set": bson.M{"members.$.role": role}},
            ReturnNew: true,
        }
    
        var updatedGroup Group
        _, err := r.db.C("groups").Find(bson.M{"members": bson.M{"$elemMatch": bson.M{"id": id}}}).Apply(change, &updatedGroup)
        if err == mgo.ErrNotFound {
            return nil, fmt.Errorf("member with ID '%s' does not exist", id)
        } else if err != nil {
            return nil, err
        }
    
        for _, member := range updatedGroup.Members {
            if member.Id == id {
                return &member, nil
            }
        }
    
        return nil, fmt.Errorf("weird error, Id cannot be found")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助