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