Go 语言在 MongoDB 中常用查询与修改的操作,你都会了吗?

时间:2025-11-04 19:50:42来源:极客码头作者:应用开发

以下所有例子中结构定义如下:复制type User struct { Id_ bson.ObjectId `bson:"_id"` Name string `bson:"name"` Age int `bson:"age"` JoinedAt time.Time `bson:"joined_at"` Interests []string `bson:"interests"` Num []int `bson:"num"` }1.2.3.4.5.6.7.8.

1、中作都查询

通过func (c *Collection) Find(query interface{}) *Query来进行查询,常用查询返回的修改Query struct可以有附加各种条件来进行过滤。

Go 语言在 MongoDB 中常用查询与修改的操作,你都会了吗?

通过Query.All()可以获得所有结果,中作都通过Query.One()可以获得一个结果,常用查询注意如果没有数据或者数量超过一个,修改One()会报错。中作都

条件用bson.M{key: value},常用查询注意key必须用MongoDB中的修改字段名,而不是中作都struct的字段名。

1.1、常用查询查询所有

复制var users []User c.Find(nil).All(&users)1.2.

上面代码可以把所有Users都查出来:

1.2、修改根据ObjectId查询

复制id := "5204af979955496907000001" objectId := bson.ObjectIdHex(id) user := new(User) c.Find(bson.M{"_id": objectId}).One(&user)1.2.3.4.

更简单的中作都方式是直接用FindId()方法:

复制c.FindId(objectId).One(&user)1.

注意这里没有处理err。WordPress模板当找不到的常用查询时候用One()方法会出错。

1.3、修改单条件查询

复制=($eq) c.Find(bson.M{"name": "Jimmy Kuu"}).All(&users) !=($ne) c.Find(bson.M{"name": bson.M{"$ne": "Jimmy Kuu"}}).All(&users) >($gt) c.Find(bson.M{"age": bson.M{"$gt": 32}}).All(&users) <($lt) c.Find(bson.M{"age": bson.M{"$lt": 32}}).All(&users) >=($gte) c.Find(bson.M{"age": bson.M{"$gte": 33}}).All(&users) <=($lte) c.Find(bson.M{"age": bson.M{"$lte": 31}}).All(&users) in($in) c.Find(bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}).All(&users)1.2.3.4.5.6.7.8.9.10.11.12.13.14.

1.4、多条件查询

复制and($and) c.Find(bson.M{"name": "Jimmy Kuu", "age": 33}).All(&users) or($or) c.Find(bson.M{"$or": []bson.M{bson.M{"name": "Jimmy Kuu"}, bson.M{"age": 31}}}).All(&users)1.2.3.4.

2、修改通过func (*Collection) Update来进行修改操作。

复制func (c *Collection) Update(selector interface{}, change interface{}) error1.

注意修改单个或多个字段需要通过$set操作符号,否则集合会被替换。

2.1、($set)

复制//修改字段的值 c.Update( bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$set": bson.M{ "name": "Jimmy Gu", "age": 34 }} )1.2.3.4.5.

2.2、inc(set)¨G7G2.2、inc(inc)

复制//字段增加值 c.Update( bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$inc": bson.M{ "age": -1 }} ) //字段Num数组第三个数增加值 c.Update( bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$inc": bson.M{ "Num." + strconv.Itoa(2): 1 }})1.2.3.4.5.6.7.8.9.

2.3、push($push)

复制//从数组中增加一个元素 c.Update( bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$push": bson.M{ "interests": "Golang" }} )1.2.3.4.5.

2.4、pull(push)¨G9G2.4、pull(pull)

复制//从数组中删除一个元素 c.Update( bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$pull": bson.M{ "interests": "Golang" }} )1.2.3.4.5.

2.5、删除

复制c.Remove(bson.M{"name": "Jimmy Kuu"})1.

补充:golang mongodb查找find demo

使用gopkg.in/mgo.v2库操作,插入操作主要使用mongodb中Collection对象的站群服务器Find方法,函数原型:

复制func (c *Collection) Find(query interface{}) *Query1.

查找的时候Find的参数都会用bson.M类型

复制type M map[string]interface{}1.

例如:bson.M{"name": "Tom"}相当直接mongodb的查询条件{"name": "Tom"}

统一封装下getDB方法 复制package main import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // get mongodb db func getDB() *mgo.Database { session, err := mgo.Dial( "172.16.27.134:10001" ) if err != nil { panic(err) } session.SetMode(mgo.Monotonic, true) db := session.DB( "test" ) return db }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20. 查找单条记录 复制func findOne() { db := getDB() c := db.C( "user" ) // 用struct接收,一般情况下都会这样处理 type User struct { Name string "bson:`name`" Age int "bson:`age`" } user := User{} err := c.Find(bson.M{ "name" : "Tom" }).One(&user) if err != nil { panic(err) } fmt.Println(user) // output: {Tom 20} // 用bson.M结构接收,当你不了解返回的数据结构格式时,可以用这个先查看,然后再定义struct格式 // 在处理mongodb组合查询时,经常这么干 result := bson.M{} err = c.Find(nil).One(&result) if err != nil { panic(err) } fmt.Println(result) // output: map[_id:ObjectIdHex("56fdce98189df8759fd61e5b") name:Tom age:20] }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29. 查找多条记录 复制func findMuit() { db := getDB() c := db.C( "user" ) // 使用All方法,一次性消耗较多内存,如果数据较多,可以考虑使用迭代器 type User struct { Id bson.ObjectId `bson: "_id,omitempty" ` Name string "bson:`name`" Age int "bson:`age`" } var users []User err := c.Find(nil).All(&users) if err != nil { panic(err) } fmt.Println(users) // output: [{ObjectIdHex("56fdce98189df8759fd61e5b") Tom 20}...] // 使用迭代器获取数据可以避免一次占用较大内存 var user User iter := c.Find(nil).Iter() for iter.Next(&user) { fmt.Println(user) } // output: // {ObjectIdHex("56fdce98189df8759fd61e5b") Tom 20} // {ObjectIdHex("56fdce98189df8759fd61e5c") Tom 20} // ... }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30. 查找指定字段 复制func (q *Query) Select(selector interface{}) *Query1.

上面使用Select函数:

复制func findField() { db := getDB() c := db.C( "user" ) // 只读取name字段 type User struct { Name string "bson:`name`" } var users []User err := c.Find(bson.M{}).Select(bson.M{ "name" : 1 }).All(&users) if err != nil { panic(err) } fmt.Println(users) // output: [{Tom} {Tom} {Anny}...] // 只排除_id字段 type User2 struct { Name string "bson:`name`" Age int "bson:`age`" } var users2 []User2 err = c.Find(bson.M{}).Select(bson.M{ "_id" : 0 }).All(&users2) if err != nil { panic(err) } fmt.Println(users2) // output: [{Tom 20} {Tom 20} {Anny 28}...] }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31. 查询嵌套格式数据 复制func findNesting() { db := getDB() c := db.C( "user" ) // 使用嵌套的struct接收数据 type User struct { Name string "bson:`name`" Age int "bson:`age`" Toys []struct { Name string "bson:`name`" } } var users User // 只查询toys字段存在的 err := c.Find(bson.M{ "toys" : bson.M{ "$exists" : true}}).One(&users) if err != nil { panic(err) } fmt.Println(users) // output: {Tom 20 [{dog}]} }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22. 查找数据总数 复制func count() { db := getDB() c := db.C( "user" ) // 查找表总数 count, err := c.Count() if err != nil { panic(err) } fmt.Println(count) // output: 8 // 结合find条件查找 count, err = c.Find(bson.M{ "name" : "Tom" }).Count() if err != nil { panic(err) } fmt.Println(count) // output: 6 }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22. 对数据进行排序使用Sort函数 复制func (q *Query) Sort(fields ...string) *Query1. 上面就是使用sort函数的方法 复制func findSort() { db := getDB() c := db.C( "user" ) type User struct { Id bson.ObjectId `bson: "_id,omitempty" ` Name string "bson:`name`" Age int "bson:`age`" } var users []User // 按照age字段降序排列,如果升序去掉横线"-"就可以了 err := c.Find(nil).Sort( "-age" ).All(&users) if err != nil { panic(err) } fmt.Println(users) // output: // [{ObjectIdHex("56fdce98189df8759fd61e5d") Anny 28} ...] // ... }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19. 分页查询使用Skip函数和Limit函数 复制func (q *Query) Skip(n int) *Query func (q *Query) Limit(n int) *Query1.2. 复制func findPage() { db := getDB() c := db.C( "user" ) type User struct { Id bson.ObjectId `bson: "_id,omitempty" ` Name string "bson:`name`" Age int "bson:`age`" } var users []User // 表示从偏移位置为2的源码库地方开始取两条记录 err := c.Find(nil).Sort( "-age" ).Skip( 2 ).Limit( 2 ).All(&users) if err != nil { panic(err) } fmt.Println(users) // output: // [{ObjectIdHex("56fdce98189df8759fd61e5d") Anny 20} ...] // ... }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.

相关内容
热点内容