我只想将对象推入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" } ] }
并将对象推入需要执行的上述文档中
db.stack.update({"ownerEmail":"john.smith@gmail.com"}, {$push: { "camps":{ "name":"cubs-killeen","location":"some other Place" } } } )
那么我如何使用 mgo驱动程序* 实现相同的功能 *
请尝试以下操作:
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) }