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

标签 mongodb go mgo

我正在尝试使用 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)

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

注意:我已经通过谷歌搜索但找不到与我需要的相关的内容。

查询 2: 我还需要像更新 details > members > obj 一样更新 details > 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
 }
]

关于mongodb - 为什么我的查询没有更新数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47900206/

相关文章:

node.js - NextJS/Vercel/MongoDB FetchError : request to http://localhost:3000/api/gear failed, 原因: connect ECONNREFUSED 127. 0.0.1:3000

go - 在客户端中获取 405 http 错误以调用 gRPC Web

使用 go 动态进行 mongodb 查询

javascript - 保护我的非规范化 Meteor 评级系统

mongodb - 使用 mgo 驱动程序,Mongodb 连接计数每 10 秒增加一个

go - 如何将数据添加到 Golang 中的 map map ?

mongodb - 监视 MongoDB 更改流

json - 将 slice 结果 JSON 插入 MongoDB

mongodb - Golang使用MongoDB报告 "context deadline exceeded"

mysql - Go 将非 ascii 形式的值保存为问号