# Connect to MongoDB using the Go Driver

• mongo.Connect Connect
• client.Ping Check the connection
• client.Disconnect Close the connection

# BSON (Binary Serialized Document Format, Binary-encoded JSON)

• 一種二進制形式的存儲格式，採用了類似於 C 語言結構體的名稱
• 對表示方法支援內嵌的文件物件和陣列物件
• 具有輕量性、可遍歷性、高效性的特點，可以有效描述非結構化數據和結構化數據
• schema-less的存儲形式
• 優點是靈活性高，但它的缺點是空間利用率不是很理想
• 不像一般 json 用簡單的 string 和 number，而是可以給予 type (int, long, date, floating point, and decimal128)，可以更方便的去做比較排許等等的

### 在 Go 中提供了兩種 BSON 的資料格式 D types the Raw types

D type

The D family of types is used to concisely build BSON objects using native Go types. This can be particularly useful for constructing commands passed to MongoDB. The D family consists of four types:

• D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.
• M: An unordered map. It is the same as D, except it does not preserve order.
• A: A BSON array.
• E: A single element inside a D.

Example

Raw

The Raw family of types is used for validating a slice of bytes. You can also retrieve single elements from Raw types using a Lookup. This is useful if you don’t want the overhead of having to unmarshall the BSON into another type. This tutorial will just use the D family of types.

# CRUD Operations

### U - Update documents

• \$inc - Increments the value of the field by the specified amount.
• updateResult.MatchedCount - The number of documents that matched the filter.
• updateResult.ModifiedCount - The number of documents that were modified.

### R - Find documents

Find a document use collection.FindOne()

To find a document, you will need a filter document as well as a pointer to a value into which the result can be decoded

Find multiple documents use collection.Find()

This method returns a Cursor. A Cursor provides a stream of documents through which you can iterate and decode one at a time. Once a Cursor has been exhausted, you should close the Cursor.

Here you’ll also set some options on the operation using the options package. Specifically, you’ll set a limit so only 2 documents are returned.

### D - Delete Documents

delete documents using collection.DeleteOne() or collection.DeleteMany().

Here you pass nil as the filter argument, which will match all documents in the collection. You could also use collection.Drop() to delete an entire collection.

Reference