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 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人