Mgo: how to update a specific array in a document
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 an array of locations if I know the storage 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 we get this error: $ elemMatch prefix field in dollars ($) in 'location. $ elemMatch 'is not valid for storage.
THX.
source to share
You wrote it wrong. A match on the "id" value in stock belongs to your carrier's "query" section, not the "Update" section. This way you don't need an option UpdateId
, but Update
since it allows a wider choice of query:
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 "dot notation" form is fine here, since your selector for an array element is just a special field. Usually you need when this array has another field in the array to match. $elemMatch
source to share