以下所有例子中结构定义如下:
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"})