mongoDB is currently the more popular a file storage based on distributed databases, it is a product with function between relational databases and non-relational databases (NoSQL), non-relational database among the most feature-rich, like most relational databases.
mongoDB Introduction
mongoDB is currently the more popular a file storage based on distributed databases, it is a product with function between relational databases and non-relational databases (NoSQL), non-relational database among the most feature-rich, like most relational databases.
MongoDB in the data is stored as a document (document), the data structure of the key (key-value) pairs. Where the document is similar to JSON objects used in our normal programming. Field value document may contain other documents, arrays and array of documents.
mongoDB related concepts
mongoDB the concepts we are familiar with SQL concepts contrast as follows:
The term & MongoDB / concepts | Explanation | Comparative SQL terms / concepts |
---|---|---|
database | database | database |
collection | set | table |
document | File | row |
field | Field | column |
index | index | index |
primary key | MongoDB automatically primary key field as the primary key _id | primary key |
mongoDB installation
We are here to download and install Community Edition, the official website Download . After opening the connection, select the corresponding version of the operating system platform (common platforms are supported) and packet type, click the Download button to download it.
Supplement here under, Windows platform ZIP
and MSI
two kinds of package types: * ZIP: compressed version of the file * MSI: executable version, click "Next" can be installed.
macOS platform in addition to downloading the page TGZ
file, you can also use Homebrew
the installation.
For more details refer to install the official installation tutorial , there are Linux
, macOS
and Windows
installation instructions for the three major platforms.
Basic use mongoDB
Start mongoDB database
Windows
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
Mac
mongod --config /usr/local/etc/mongod.conf
or
brew services start [email protected]
Start client
Windows
"C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
Mac
mongo
Database commonly used commands
show dbs;
: View Database
> show dbs; admin 0.000GB config 0.000GB local 0.000GB test 0.000GB
use q1mi;
: Switch to the specified database, if the database does not exist is created.
> use q1mi; switched to db q1mi
db;
: Displays the current location database.
> db; q1mi
db.dropDatabase()
: Delete the current database
> db.dropDatabase(); { "ok" : 1 }
Data sets commonly used commands
db.createCollection(name,options)
: Creating a Data Set
- name: dataset name
- options: An optional parameter specifies the memory size and index.
> db.createCollection("student"); { "ok" : 1 }
show collections;
: View all collections in the current database.
> show collections; student
db.student.drop()
: Delete the specified data set
> db.student.drop() true
Documents commonly used commands
Insert a document:
> db.student.insertOne({name:"小王子",age:18}); { "acknowledged" : true, "insertedId" : ObjectId("5db149e904b33457f8c02509") }
Insert multiple documents:
> db.student.insertMany([ ... {name:"张三",age:20}, ... {name:"李四",age:25} ... ]); { "acknowledged" : true, "insertedIds" : [ ObjectId("5db14c4704b33457f8c0250a"), ObjectId("5db14c4704b33457f8c0250b") ] }
Query all documents:
> db.student.find(); { "_id" : ObjectId("5db149e904b33457f8c02509"), "name" : "小王子", "age" : 18 } { "_id" : ObjectId("5db14c4704b33457f8c0250a"), "name" : "张三", "age" : 20 } { "_id" : ObjectId("5db14c4704b33457f8c0250b"), "name" : "李四", "age" : 25 }
Query age> 20-year-old document:
> db.student.find( ... {age:{$gt:20}} ... ) { "_id" : ObjectId("5db14c4704b33457f8c0250b"), "name" : "李四", "age" : 25 }
Update documents:
> db.student.update( ... {name:"小王子"}, ... {name:"老王子",age:98} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.student.find() { "_id" : ObjectId("5db149e904b33457f8c02509"), "name" : "老王子", "age" : 98 } { "_id" : ObjectId("5db14c4704b33457f8c0250a"), "name" : "张三", "age" : 20 } { "_id" : ObjectId("5db14c4704b33457f8c0250b"), "name" : "李四", "age" : 25 }
Delete the document:
> db.student.deleteOne({name:"李四"}); { "acknowledged" : true, "deletedCount" : 1 } > db.student.find() { "_id" : ObjectId("5db149e904b33457f8c02509"), "name" : "老王子", "age" : 98 } { "_id" : ObjectId("5db14c4704b33457f8c0250a"), "name" : "张三", "age" : 20 }
Command too many more commands refer to the official documentation: shell command and the official document: CRUD operations .
Go language operating mongoDB
We use here is the official driver package, of course, you can also use a third-party driver packages (such as mgo, etc.). mongoDB official version of the Go drive released relatively late (13th December 2018).
Driver package installation mongoDB Go
go get github.com/mongodb/mongo-go-driver
MongoDB connected via the Go
package main import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { // 设置客户端连接配置 clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // 连接到MongoDB client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } // 检查连接 err = client.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!") }
After connecting the MongoDB, it can be treated by the following statement above q1mi our database of student data set:
// Get the specified data set to be operated in the collection:. = Client.Database ( "q1mi ") Collection ( "student")
After processing tasks can disconnect MongoDB by the following command:
// 断开连接 err = client.Disconnect(context.TODO()) if err != nil { log.Fatal(err) } fmt.Println("Connection to MongoDB closed.")
Connection Pool Mode
import ( "context" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func ConnectToDB(uri, name string, timeout time.Duration, num uint64) (*mongo.Database, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() o := options.Client().ApplyURI(uri) o.SetMaxPoolSize(num) client, err := mongo.Connect(ctx, o) if err != nil { return nil, err } return client.Database(name), nil }
BSON
JSON documents stored in MongoDB named BSON (JSON binary-encoded) binary representation. Simple strings and numbers of the other databases with different data storage JSON, JSON represents the BSON encoding expanded to include additional types, such as int, long, date, floating point and decimal128. This makes the application more easily and reliably handling, sorting and comparing data.
Go MongoDB driver to connect, there are two types of data representation BSON: D
and Raw
.
Type D
family was used to construct a local Go succinctly BSON type objects. This is particularly useful for MongoDB configuration command to pass. D
Family includes four categories:
- D: a BSON document. This type should be used in case the order is important, such as MongoDB command.
- M: a disorder of the map. D and it is the same, except that it does not maintain order.
- A: a BSON array.
- E: D an element inside.
To use BSON, you need to import the following packages:
import "go.mongodb.org/mongo-driver/bson"
The following is an example of a filter constructed in the document using the D type, which can be used to find the name field with 'John Doe' or 'John Doe' matching documents:
bson.D{{ "name", bson.D{{ "$in", bson.A{"张三", "李四"}, }}, }}
Raw
Family type used to verify byte slice. You can also use Lookup()
to retrieve a single element from the original type. If you do not want to BSON anti-sequence into another type of spending, then this is very useful. This tutorial we will use only the D type.
CRUD
We now define a code Go Studet
types are as follows:
type Student struct { Name string Age int }
Next, create some Student
value types, ready to be inserted into the database:
s1: = Student { "red", 12 is} S2: {= Student "orchid", 10} S3: = {Student "Huang", 11}
Insert Document
Using the collection.InsertOne()
method of inserting a documentation:
insertResult, err := collection.InsertOne(context.TODO(), s1) if err != nil { log.Fatal(err) } fmt.Println("Inserted a single document: ", insertResult.InsertedID)
Use collection.InsertMany()
method to insert multiple documented:
students := []interface{}{s2, s3} insertManyResult, err := collection.InsertMany(context.TODO(), students) if err != nil { log.Fatal(err) } fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
Update Documentation
updateone()
Method allows you to update a single document. It requires a document to match the filter documents in the database, and requires an updated document that describes the update operation. You can use bson.D
to build and update the document screening document type:
filter := bson.D{{"name", "小兰"}} update := bson.D{ {"$inc", bson.D{ {"age", 1}, }}, }
Next, you can find the following statement by Betty, gave him increased one year old:
updateResult, err := collection.UpdateOne(context.TODO(), filter, update) if err != nil { log.Fatal(err) } fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
Finding Documentation
To find a document, you need a filter file, and a pointer to the results can be decoded its value. To find a single document, use collection.FindOne()
. This method returns a result value to be decoded.
We had to use that filter defined above to find the name to 'Betty' documents.
// Create a Student variable for receiving query results var Result Student ERR = collection.FindOne (context.TODO (), filter) .Decode (& Result) IF ERR! = Nil { log.Fatal (ERR) } fmt.Printf ( "Found a single document:% + v \ n", result)
To find multiple documents, use collection.Find()
. This method returns a cursor. Cursors provide a document flow, you can first iteration and decoding a document through it. When the cursor is used up, the cursor should be closed. The following example uses the options
package to set a limit to return only two documents.
// query multiple // pass options to the Find () findOptions: = options.Find () findOptions.SetLimit (2) // define sections for storing a query result var Results [] * Student // put bson.D {} {} as a filter to match all documents CUR, ERR: = collection.Find (context.TODO (), {} {} bson.D, findOptions) ! IF ERR = nil { log.Fatal (ERR) } / / find multiple documents returns a cursor // cursor traversing a decoding time allows us to document for cur.Next (context.TODO ()) { // create a value, the value of a single document for the decoding var elem Student ERR: = CUR .Decode (& elem) ! IF ERR = nil { log.Fatal (ERR) } Results = the append (Results, & elem) } IF ERR: = cur.Err (); ERR = nil {! log.Fatal (ERR) } / after / cursor off completion cur.Close(context.TODO()) fmt.Printf("Found multiple documents (array of pointers): %#v\n", results)
Delete Document
Finally, you can use collection.DeleteOne()
or collection.DeleteMany()
delete documents. If you pass bson.D{{}}
all of the documents as a filter parameter, it will match the data set. Also can be used collection. drop()
to delete the entire data set.
// 删除名字是小黄的那个 deleteResult1, err := collection.DeleteOne(context.TODO(), bson.D{{"name","小黄"}}) if err != nil { log.Fatal(err) } fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult1.DeletedCount) // 删除所有 deleteResult2, err := collection.DeleteMany(context.TODO(), bson.D{{}}) if err != nil { log.Fatal(err) } fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult2.DeletedCount)
More ways to consult the official documentation .
Reference links
https://docs.mongodb.com/manual/mongo/
https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial
Reprinted from Li Zhou blog