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

Why my query is not updating the object inside an array?

我正在尝试使用 mgo 更新文档数组中的对象。对象结构如下:

{
"_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
            }
        }
    ]
}]
}

查询 1: 我首先尝试更新 details > obj,其中尝试使用以下查询

添加另一个属性 "guava": 15
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)

此查询既没有产生任何错误也没有更新文档。谁能告诉我怎样才能完成它

注意:我搜索了 google 但找不到与我需要的相关的内容。

查询 2: 我还需要像更新 details > obj 一样更新 details > members > obj。还请告诉我如何为 details > members > obj.

实现相同的效果

我花了几个小时来解决这个问题,但没有解决。如果有人能指导我,我将不胜感激。

为了简单,我删除了成员。

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\n", 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\n", string(data))
}

结果:

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
 }
]