mongodb入门之增删改查
相关概念
MongoDB术语/概念 |
说明 |
对比SQL术语/概念 |
database |
数据库 |
database |
collection |
集合 |
table |
document |
文档 |
row |
field |
字段 |
column |
index |
index |
索引 |
primary key |
主键 MongoDB自动将_id字段设置为主键 |
primary key |
Docker容器运行mongo服务
docker run -d --name=mymongo --restart=always -p 27017:27017 mongo:latest
使用mongo
进入mongo解释器
docker exec -i -t mymongo mongo
数据库相关命令
show dbs

use hello

db

db.dropDatabase()

集合常用命令
show collections
db.createCollection("student")

db.student.drop()

文档常用命令
db.student.insertOne({"name":"gocloudcoder","age":21})
db.student.insertMany([ {name:"ch",age:21}, {name:"dww",age:21}])
db.student.find()

db.student.update({"name":"dww"},{"name":"dww", "age":18})

db.student.deleteOne({"name":"dww"})

db.student.find({"age":21}) # 查询年龄等于21
操作 |
格式 |
范例 |
RDBMS中的类似语句 |
等于 |
{<key>:<value> } |
db.student.find({"age":21}).pretty() |
where age = 21 |
小于 |
{<key>:{$lt:<value>}} |
db.student.find({"age":{$lt:21}}).pretty() |
where age < 21 |
小于或等于 |
{<key>:{$lte:<value>}} |
db.student.find({"age":{$lte:21}}).pretty() |
where age <= 21 |
大于 |
{<key>:{$gt:<value>}} |
db.student.find({"age":{$gt:21}}).pretty() |
where age > 21 |
大于或等于 |
{<key>:{$gte:<value>}} |
db.studentl.find({"age":{$gte:21}}).pretty() |
where age >= 21 |
不等于 |
{<key>:{$ne:<value>}} |
db.student.find({"age":{$ne:21}}).pretty() |
where age != 50 |
go操作mongodb
package mainimport ( "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) defer client.Disconnect(context.TODO()) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!")}
//指定获取要操作的集合collection := client.Database("hello").Collection("student")
type Student struct { Name string Age int32}s1 := Student{ Name : "zyf", Age : 21, }res, err := collection.InsertOne(context.TODO(), s1)if err != nil { log.Fatal(err)}
s2 := Student{ Name: "gocloudcoder", Age: 22, }s3 := Student{ Name: "hs", Age: 21,}resm, err := collection.InsertMany(context.TODO(), []interface{}{s2, s3})if err != nil { fmt.Println(err)}
filter := bson.D{{"name", "njnj"}}update := bson.M{"$set":Student{Name: "njnjnj"}}one, err := collection.UpdateOne(context.TODO(), filter, update)if err != nil { log.Fatal(err)}
var stu Studenterr = collection.FindOne(context.TODO(), filter).Decode(&stu)if err != nil { log.Fatal(err)}fmt.Println(stu)
filter := bson.D{{"name", "zyf"}}res, err := collection.DeleteOne(context.TODO(), filter)if err != nil { log.Fatal(err)}fmt.Println(res.DeletedCount)