golang mongo-driver 使用基础

晋俊贤
2023-12-01

BSON是什么?

BSON就是二进制编码的JSON序列化数据。

官网上提到的三个特点有:

  1. 更轻量
  2. 可转换(序列化和反序列化)
  3. 更高效,因为是二进制的

BSON在mongdo-driver中的应用

根据上面所说的BSON的特点,MongoDB是用BSON作为主要的数据格式

go.mongodb.org/mongo-driver/bson 的使用

bson struct

在进行mongodb操作时,经常需要一些基本的bson结构体。有四种struct可以定义bson的数据结构:bson.D{}bson.E{}bson.M{}bson.A{}

先贴上bson.go的源码,其实说得很清楚了

// D is an ordered representation of a BSON document. This type should be used when the order of the elements matters,
// such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.
//
// Example usage:
//
// 		bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}
type D = primitive.D

// E represents a BSON element for a D. It is usually used inside a D.
type E = primitive.E

// M is an unordered representation of a BSON document. This type should be used when the order of the elements does not
// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be
// serialized in an undefined, random order. If the order of the elements matters, a D should be used instead.
//
// Example usage:
//
// 		bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}
type M = primitive.M

// An A is an ordered representation of a BSON array.
//
// Example usage:
//
// 		bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}}
type A = primitive.A

bson/primitive

primitive package定义了一些使用mongodb过程中常用的数据结构和操作数据结构的方法

ObjectID

类型定义使用:primitive.ObjectID

新建一个ObjectID:primitive.NewObjectID()

正则匹配Regex

源码

// Regex represents a BSON regex value.
type Regex struct {
	Pattern string
	Options string
}

func (rp Regex) String() string {
	return fmt.Sprintf(`{"pattern": "%s", "options": "%s"}`, rp.Pattern, rp.Options)
}

// Equal compares rp to rp2 and returns true is the are equal.
func (rp Regex) Equal(rp2 Regex) bool {
	return rp.Pattern == rp2.Pattern && rp.Options == rp2.Options
}

// IsZero returns if rp is the empty Regex
func (rp Regex) IsZero() bool {
	return rp.Pattern == "" && rp.Options == ""
}

使用例子

condition := bson.D{}
if cond.Title != "" {
	condition = append(condition, bson.E{"title", primitive.Regex{Pattern:cond.Title, Options:"i"}})
}

待补充

 类似资料: