MongoDB配置与基础用法

MongoDB 安装

官网:https://www.mongodb.com/

手册:https://docs.mongodb.org/manual/

win7系统需要安装补丁,KB2731284

  • 安装完成配置环境变量:
  • C:Program FilesMongoDBServer3.0in 加入到系统的path环境变量中

基础命令

  • gongod: 开机
  • mongoimport 导入数据
  • mongo 使用数据库,运行此命令后的环境就是mongo语法了
  • show dbs:列出所有数据库
  • use 数据库名字:使用某个数据库
  • db:查看当前所在数据库

注意:如果use一个不存在的数据库就是新建,但是只有执行插入数据语句后才能新建成功。

数据库的使用

要管理数据库,必须先开机,开机使用mongod --dbpath c:mongom命令(--dbpath就是选择数据库文档所在的文件夹)

1.插入数据

  • 普通插入

    db.student.insert({"name":"xiaoming"});

  • 导入数据

    /*
     * db test 想往哪个数据库里面导入
     * collection restaurants 想往哪个集合中导入
     * drop 把集合清空
     * file primer-dataset.json 哪个文件
     */ 
    mongoimport --db test --collection restaurants --drop --file primer-dataset.json

2.查询数据

  • 查询全部

    db.restaurants.find()

  • 精确匹配

    db.student.find({"score.shuxue":80});

  • 多个条件

    db.student.find({"score.shuxue":80 , "age":22})

  • 大于条件

    db.student.find({"score.yuwen":{$gt:60}});

  • db.student.find({$or:[{"age":18},{"age":22}]});

  • 排序

    db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } )

3.修改数据

  • 单条数据修改

    db.student.update({"name":"小明"},{$set:{"age":22}});

  • 更改多条匹配数据(加上multi参数)

    db.student.update({"score.shuxue":80},{$set:{"age":26}},{multi: true});

  • 完成替换(不加$set关键字)

    db.student.update({"name":"小明"},{"name":"大明","age":28});

4.删除数据

  • db.restaurants.remove( { "borough": "Manhattan" } )

原文地址:https://www.cnblogs.com/Doduo/p/8206156.html