douwei1944 2014-08-02 09:41
浏览 106
已采纳

mgo:如何更新文档中的特定数组

I have this document inside my database

[
  {
    "_id": "53dc97bf91f1f933e15d6fb1",
    "attributes": {
      "chilled": false,
      "flammable": false,
      "food": false,
      "fragile": false,
      "frozen": false,
      "hot": false,
      "outsized": false
    },
    "createdAt": "02/08/14 09:48:16",
    "customer": "53d68bc091f1f933e15d6f90",
    "location": [
      {
        "count": 0,
        "warehouse": "53db430c91f1f933e15d6fa6"
      },
      {
        "count": 34,
        "warehouse": "53db430c91g1f933e45d6fa4"
      },
    ],
    "name": "test",
    "type": "stored",
    "updatedAt": ""
  }
]

How can i update the location array if i know the warehouse Id? This is what i have now

coll := p.GetDb().C("product")
    changes := bson.M {
        "location": bson.M {
            "$elemMatch": bson.M {
                "warehouse": bson.ObjectIdHex(warehouseId),
            },
        },
        "$set": bson.M {
            "location.$.count": 4,
        }, 
    }

    err := coll.UpdateId(bson.ObjectIdHex(productId), changes)
    if err != nil {
        http.Error(res, err.Error(), 500)
        return
    }

But get this error: The dollar ($) prefixed field '$elemMatch' in 'location.$elemMatch' is not valid for storage.

thx.

  • 写回答

1条回答 默认 最新

  • dounai1986 2014-08-02 10:09
    关注

    You wrote this the wrong way around. The match on the warehouse "id" value belongs in the "query" portion of your statement and not in the "update" section. As such, you don't want the UpdateId variant, but the Update as it allows a wider query selection:

    query := bson.M{
        "_id": bson.ObjectIdHex(productId),
        "location.warehouse": bson.ObjectIdHex(warehouseId)
    }
    
    update := bson.M{
        "$set": bson.M{
            "location.$.count": 4
        }
    }
    
    err := coll.Update(query,update)
    

    Also note that the the "dot notation" form is fine here as your selector for the array element is just a singular field. You typically only need $elemMatch when there is more that one field in the array to establish the match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?