小编典典

MongoDb:如何在golang中的对象集合中插入其他对象?

go

我只想将对象推入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驱动程序* 实现相同的功能 *


阅读 304

收藏
2020-07-02

共1个答案

小编典典

请尝试以下操作:

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)
}
2020-07-02