工作生活

MongoDB入门操作案例

2019-07-02  本文已影响0人  AI迟到

安装

启动

连接

命令行中输入mongo即可进入MongoDB客户端,如果通过程序访问数据库一定要设置端口号,退出exit

操作

1.查看数据库show databasesshow dbs
2.使用/创建数据库use test当进入一个不存在的数据库即创建一个数据库,例如use mldn 此时创建了一个新的数据库,但是当你show dbs时并不会出现,mongdb真正创建这个库是在你库里面创建一个集合或者插入一条数据的时候。

查看操作
3.db.createCollection("emp")创建一个集合,在mysql中数据库中存放的是表,在mongodb中我们叫它集合,换汤不换药,理解一哈就行,mysql中表中存放的是一行一行的数据,在mogodb中我们叫文档,名字不重要,知道有这么个东西就OK。
4.show collections查看所有集合
5db.emp.insert({"deptno":10,"dname":"财务部","loc":"北京"})向集合中插入一条数据
6.db.emp.find()查看集合中数据
查看集合中数据
7.db.集合.drop删除一个集合
8.删除一个数据库,需要use 数据库名,而后执行db.dropDatabase()操作
9.条件查询,测试数据
db.student.insert({"name":"李四","sex":"男","age":19,"score":89})
db.student.insert({"name":"赵五","sex":"男","age":19,"score":89})
db.student.insert({"name":"钱六","sex":"男","age":16,"score":89})
db.student.insert({"name":"张七","sex":"男","age":17,"score":89})
db.student.insert({"name":"张八","sex":"男","age":18,"score":89})
db.student.insert({"name":"张一","sex":"男","age":19,"score":89})
db.student.insert({"name":"张二","sex":"男","age":20,"score":89})
db.student.insert({"name":"张十","sex":"男","age":21,"score":89})
db.student.insert({"name":"张九","sex":"男","age":19,"score":89})

(使用pretty()方法是为了美化查询结果数据,方便查看)

  1. 数据分页显示
  1. 删除数据
    使用remove
    删除条件:满足删除条件得删除,是否只删除一个数据,如果设置为true1表示只删除一个数据
    范例:删除所有姓名带有张字的同学信息
    db.student.remove({"name":/张/})
    db.student.remove({"name":/张/},true)
    清空所有数据操作
    db.student.remove({})
上一篇 下一篇

猜你喜欢

热点阅读