Mongodb的基本命令及增删改查:
show dbs
show databases;
use 数据库名 #进入数据库,如果数据库没有会自动创建
#####增删改查:
1.插入数据:
db.<collection>.insert(doc)
- 向集合中插入一个文档
-例子: 向test数据库中的,stus集合中插入一个新的学生对象
{name:"孙悟空",age:18,gender:"男"}
db.stus.insert({name:"孙悟空",age:18,gender:"男"})
db.<collection>.find()
##################
> use test
switched to db test
> db
test
> db.stus.insert({name:"sunwukong",age:18,gender:"nanmale"})
WriteResult({ "nInserted" : 1 })
>
查找刚刚创建的数据:
> db.stus.find();
{ "_id" : ObjectId("656060425995e681014e7c0d"), "name" : "sunwukong", "age" : 18, "gender" : "nanmale" }
####################################################################
insert语句:
##插入一个数据:
> db.stus.insert({name:"zhangsan",age:19,gender:"male"})
WriteResult({ "nInserted" : 1 })
##插入几个数据:
db.stus.insert([
{"name" : "wangwu", "age":25, gender:"男"},
{"name" : "蜘蛛精", "age" :100, "gender":"女"},
{"name" : "赵六", "age":39, "gender":"男"}
])
> db.stus.insert({name:"zhangsan",age:19,gender:"male"}) WriteResult({ "nInserted" : 1 }) > db.find(); uncaught exception: TypeError: db.find is not a function : @(shell):1:1 > db.stus.find(); { "_id" : ObjectId("65644f6042dc283695a317d0"), "name" : "sanzhang", "age" : 35, "gender" : "nanmale" } { "_id" : ObjectId("65645b9442dc283695a317d1"), "name" : "李四", "age" : 57, "gender" : "男" } { "_id" : ObjectId("65645c0d42dc283695a317d4"), "name" : "李四", "age" : 57, "gender" : "男" } { "_id" : ObjectId("65645e71aff3006ace840243"), "name" : "wangwu", "age" : 25, "gender" : "男" } { "_id" : ObjectId("65645e71aff3006ace840244"), "name" : "蜘蛛精", "age" : 100, "gender" : "女" } { "_id" : ObjectId("65645e71aff3006ace840245"), "name" : "赵六", "age" : 39, "gender" : "男" } { "_id" : ObjectId("65645f6caff3006ace840246"), "name" : "zhangsan", "age" : 19, "gender" : "male" }
##自定义_id
db.stus.insert({_id:"hello",name:"zhangsan",age:19,gender:"male"})
###查询语句
db.stus.find()
db.stus.find({})大括号作为条件查询,查单个条件信息
> db.stus.find({name:"zhangsan"})
{ "_id" : ObjectId("65645f6caff3006ace840246"), "name" : "zhangsan", "age" : 19, "gender" : "male" }
> db.stus.find({name:"sanzhang"})
{ "_id" : ObjectId("65644f6042dc283695a317d0"), "name" : "sanzhang", "age" : 35, "gender" : "nanmale" }
db.stus.findOne();
{ "_id" : ObjectId("65644f6042dc283695a317d0"), "name" : "sanzhang", "age" : 35, "gender" : "nanmale" }
##查询所有结果的数量:
修改语句:
db.stus.update({name:'sanzhang'},
{$set:
{address:"大唐"}
}
)
DeprecationWarning: Collection.update() is deprecated. Use updateOne, updateMany, or bulkWrite.
db.stus.update({name:'sanzhang'},{$set:{name:"xiongba"}});
##去掉名称:
db.stus.update({name:'xiongba'},{$unset:{name:"xiongba"}});
##删除语句
remove 默认单个或者多个文档(只要符合过滤条件filter)
##remove 只删一个,指定true:
##清空集合 传递空对象
db.stus.remove({})
删除集合 db.collection.drop()
删除数据库 db.dropDatabase()
更新为1为删除,就可以理解为删除:并不执行删除操作,以更新操作代替删除操作