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

时间:2015-04-23 08:16:56

标签: mongodb 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 driver

实现相同的功能

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:0)

我假设您的代码库具有 Camps 结构,类似于:

type Camps struct {
    Name     string   `json:"name,omitempty"`
    Location string   `json:"location,omitempty"`
 }

Golang代码:

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)
 }