I want just push object into array of objects in mongodb
{
"_id" : ObjectId("51c9cf2b206dfb73d666ae07"),
"firstName" : "john",
"lastName" : "smith",
"ownerEmail" : "john.smith@gmail.com",
"camps" : [
{
"name" : "cubs-killeen",
"location" : "killeen"
},
{
"name" : "cubs-temple",
"location" : "temple"
}
],
"instructors" : [
{
"firstName" : "joe",
"lastName" : "black"
},
{
"firstName" : "will",
"lastName" : "smith"
}
]
}
and to push object into above document in need to do
db.stack.update({"ownerEmail":"john.smith@gmail.com"},
{$push: {
"camps":{ "name":"cubs-killeen","location":"some other Place" }
}
}
)
So how can i implement same functionality using mgo driver
Try the following:
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Drop Database
if IsDrop {
err = session.DB("test").DropDatabase()
if err != nil {
panic(err)
}
}
// Collection Stack
c := session.DB("test").C("stack")
// Query
query := bson.M{"ownerEmail": "john.smith@gmail.com"}
update := bson.M{"$push": bson.M{"camps": bson.M{"name": "cubs-killeen", "location": "some other Place"}}}
// Update
err = c.Update(query, update)
if err != nil {
panic(err)
}
I assume your codebase has Camps struct similar to:
type Camps struct {
Name string `json:"name,omitempty"`
Location string `json:"location,omitempty"`
}
Golang code:
database := "yourDatabaseName"
collection := "stack"
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB(database).C(collection)
data := model.Camps{
Name: "cubs-killeen",
Location: "some other Place",
}
selector := bson.M{"ownerEmail": "john.smith@gmail.com"}
changes := bson.M{"$push": bson.M{"camps": bson.M{"$each": []model.Camps{data}}}}
err = c.Update(selector, changes)
if err != nil {
panic(err)
}