MongoDB:如何在Golang中将附加对象插入到对象集合中?

huangapple go评论89阅读模式
英文:

MongoDb : How to insert additional object into object collection in golang?

问题

我只会翻译你提供的内容,以下是翻译好的部分:

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

英文:

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

答案1

得分: 2

尝试以下代码:

session, err := mgo.Dial("127.0.0.1")
if err != nil {
    panic(err)
}

defer session.Close()

session.SetMode(mgo.Monotonic, true)

// 删除数据库
if IsDrop {
    err = session.DB("test").DropDatabase()
    if err != nil {
        panic(err)
    }
}

// 集合 Stack
c := session.DB("test").C("stack")

// 查询
query := bson.M{"ownerEmail": "john.smith@gmail.com"}
update := bson.M{"$push": bson.M{"camps": bson.M{"name": "cubs-killeen", "location": "some other Place"}}}

// 更新
err = c.Update(query, update)
if err != nil {
    panic(err)
}

这是一个使用 mgo 包进行 MongoDB 操作的示例代码。它连接到本地的 MongoDB 服务器,设置会话模式为 Monotonic,然后执行一些操作,包括删除数据库、查询和更新。

英文:

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

答案2

得分: 2

我假设你的代码库中有一个类似于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)
}

请注意,这只是一个示例代码,具体的数据库名称、集合名称和其他参数需要根据你的实际情况进行修改。

英文:

I assume your codebase has Camps struct similar to:

<!-- begin snippet: js hide: false console: true babel: false -->
type Camps struct {
	Name     string   `json:"name,omitempty"`
	Location string   `json:"location,omitempty"`
 }

<!-- end snippet -->

Golang code:

<!-- begin snippet: js hide: false console: true babel: false -->
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)
 }


<!-- end snippet -->

huangapple
  • 本文由 发表于 2015年4月23日 16:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/29817535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定