MongoDb:如何在golang的对象集合中插入额外的对象?
我只想将对象推入mongodb中的对象数组中MongoDb:如何在golang的对象集合中插入额外的对象?,mongodb,go,Mongodb,Go,我只想将对象推入mongodb中的对象数组中 { "_id" : ObjectId("51c9cf2b206dfb73d666ae07"), "firstName" : "john", "lastName" : "smith", "ownerEmail" : "john.smith@gmail.com", "camps" : [ { "name" : "cubs-killeen",
{
"_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)
}
我假设您的代码库的结构类似于:
type Camps struct {
Name string `json:"name,omitempty"`
Location string `json:"location,omitempty"`
}
戈朗代码:
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)
}
thanx用于澄清ans@AkashShinde不用担心:-)上面的方法是将元素添加为array@AkashShinde我想在你的问题中,这就是你想要的更新。运算符将指定的值附加到数组。考虑使用运算符,它将一个值添加到数组中,除非该值已经存在,在这种情况下对数组没有任何作用。抱歉,您的代码工作正常,我错了,我将数组添加到数组中,没有必要,请编辑标题。此外,请不要滥用粗体标记。