mongoDB数据库导入数据

利用mongoose创建数据库,基本操作

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost:27017/playground', { useNewUrlParser: true})
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));C

// 创建集合规则
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublished: Boolean
});

// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) // courses

// 创建文档
const course = new Course({
    name: 'node.js基础',
    author: 'marco',
    isPublished: true
});

// 向集合中插入文档
Course.create({name: 'Javascript', author: 'maoco', isPublished: false}, (err, result) => {
    console.log(err)
    console.log(result)
})

// 将文档插入到数据库中
course.save();

 

2. mongoDB数据库导入数据

mongoimport –d 数据库名称 –c 集合名称 –file 要导入的数据文件
找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中

找到mongoimport的安装目录

 

 

添加到系统环境变量

 

 找到要导入数据的目录, user.json, 然后在改目录下打开命令终端,输入命令;mongoimport -d playground -c  users -file ./user.json , 即可将数据导入数据库playground中的users集合中

 

 user.json数据

{"_id":{"$oid":"5c09f1e5aeb04b22f8460965"},"name":"张三","age":20,"hobbies":["足球","篮球","橄榄球"],"email":"zhangsan@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f236aeb04b22f8460967"},"name":"李四","age":10,"hobbies":["足球","篮球"],"email":"lisi@itcast.cn","password":"654321"}
{"_id":{"$oid":"5c09f267aeb04b22f8460968"},"name":"王五","age":25,"hobbies":["敲代码"],"email":"wangwu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f294aeb04b22f8460969"},"name":"赵六","age":50,"hobbies":["吃饭","睡觉","打豆豆"],"email":"zhaoliu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2b6aeb04b22f846096a"},"name":"王二麻子","age":32,"hobbies":["吃饭"],"email":"wangermazi@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2d9aeb04b22f846096b"},"name":"狗蛋","age":14,"hobbies":["打豆豆"],"email":"goudan@163.com","password":"123456"}

输入命令

 

 打开可视化数据库工具compass,可看到数据已成功导入

 

posted @ 2021-03-10 15:37  全情海洋  阅读(5191)  评论(0编辑  收藏  举报