drxp993551 2017-12-20 06:44
浏览 13
已采纳

为什么我的查询没有更新数组内的对象?

I am trying to update an object inside an array of a document using mgo. The object structure is as following:

{
"_id": 2,
"status": 0,
"details": [{
    "id": 2,
    "category": "A",
    "obj": {
        "apple": 5,
        "banana": 2,
        "cherry": 10
    },
    "members": [{
            "id": 3,
            "category": "A",
            "obj": {
                "apple": 5,
                "banana": 2,
                "cherry": 10
            }
        },
        {
            "id": 4,
            "category": "A",
            "obj": {
                "apple": 5,
                "banana": 2,
                "cherry": 10
            }
        }
    ]
}]
}

Query1: I am first trying to update details > obj where trying to add another attribute "guava": 15 using the following query

cond  := bson.M{ "$and": []bson.M{ bson.M{"document.details":bson.M{ "$elemMatch": bson.M{ "category": "A"} } }, bson.M{"document.status":0} } }
query := bson.M{ "$set": bson.M{ "document.details.$.obj.guava":15 } }
_, err := models.DbUpdateAll(Collection, cond, query)

This query is neither producing any error nor updating the doc. Can anyone please tell how can I accomplish it

Note: I have searched over google but could not find relevant to what I need.

Query2: I also need to update the details > members > obj the same way I am trying to do for details > obj. Please also tell me how can I achieve the same for details > members > obj.

I have spent hours on figuring this out but nothing worked out. I shall be thankful if anyone could guide me.

  • 写回答

1条回答 默认 最新

  • duanchifo2866 2017-12-20 08:46
    关注

    For simple, I delete the members.

    package main
    
    import (
        "fmt"
        "encoding/json"
    
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
    )
    
    func main() {
        session, err := mgo.Dial("127.0.0.1")
        if err != nil {
           panic(err)
        }
    
        defer session.Close()
    
        // Optional. Switch the session to a monotonic behavior.
        session.SetMode(mgo.Monotonic, true)
        c := session.DB("test").C("mgo")
    
        cond := bson.M{"$and": []bson.M{bson.M{"details": bson.M{"$elemMatch": bson.M{"category": "A"}}}, bson.M{"status": 0}}}
        query := bson.M{"$set": bson.M{"details.$.obj.guava": 15}}
    
        res := []interface{}{}
        err = c.Find(cond).All(&res)
    
        if err != nil {
            fmt.Println("Before Update Read Error:", err)
            return
        }
    
        data, _ := json.MarshalIndent(res, "", " ")
        fmt.Printf("Before Update Read: %s
    ", string(data))
    
        err = c.Update(cond, query)
    
        if err != nil {
            fmt.Println("Update Error:", err)
            return
        }
    
        fmt.Println("Update Succeed!")
    
        err = c.Find(cond).All(&res)
        if err != nil {
            fmt.Println("After Update Read Error:", err)
            return
        }
    
        data, _ = json.MarshalIndent(res, "", " ")
        fmt.Printf("After Update Read: %s
    ", string(data))
    }
    

    Result:

    Before Update Read: [
     {
      "_id": 2,
      "details": [
       {
        "category": "A",
        "id": 2,
        "obj": {
         "apple": 5,
         "banana": 2,
         "cherry": 10
        }
       }
      ],
      "status": 0
     }
    ]
    
    Update Succeed!
    
    After Update Read: [
     {
      "_id": 2,
      "details": [
       {
        "category": "A",
        "id": 2,
        "obj": {
         "apple": 5,
         "banana": 2,
         "cherry": 10,
         "guava": 15
        }
       }
      ],
      "status": 0
     }
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题