Go 在 MongoDB 中常用查询与修改

本文详细介绍了如何使用Go语言进行MongoDB数据库的查询与修改操作,包括查询所有记录、根据ObjectId查询、单条件和多条件查询。在修改部分,涵盖了$set、$inc、$push、$pull及删除等常见操作。示例代码清晰地展示了各个操作的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下所有例子中结构定义如下:

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、查询

通过func (c *Collection) Find(query interface{}) *Query来进行查询,返回的Query struct可以有附加各种条件来进行过滤。
通过Query.All()可以获得所有结果,通过Query.One()可以获得一个结果,注意如果没有数据或者数量超过一个,One()会报错。
条件用bson.M{key: value},注意key必须用MongoDB中的字段名,而不是struct的字段名。

1.1、查询所有
var users []User
c.Find(nil).All(&users)

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

1.2、根据ObjectId查询
id := "5204af979955496907000001"
objectId := bson.ObjectIdHex(id)
user := new(User)
c.Find(bson.M{"_id": objectId}).One(&user)

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

c.FindId(objectId).One(&user)

注意这里没有处理err。当找不到的时候用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.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)

2、修改

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

func (c *Collection) Update(selector interface{}, change interface{}) error

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

2.1、($set)
//修改字段的值
c.Update(
    bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
    bson.M{"$set": bson.M{ "name": "Jimmy Gu", "age": 34 }}
)
2.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 }})
2.3、push($push)
//从数组中增加一个元素
c.Update(
    bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
    bson.M{"$push": bson.M{ "interests": "Golang" }}
)
2.4、pull($pull)
//从数组中删除一个元素
c.Update(
    bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
    bson.M{"$pull": bson.M{ "interests": "Golang" }}
)
2.5、删除
c.Remove(bson.M{"name": "Jimmy Kuu"})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值