匯入json資料到資料庫
mongoimport -d playground -c user --file ./user.json
如果匯入不成功 ,在電腦環境變數PATH添加MongoDB的路徑,
1 // 引入mongoose第三方模塊 用來操作資料庫 2 const mongoose = require('mongoose'); 3 // 資料庫連接 4 mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true , useNewUrlParser: true }) 5 // 連接成功 6 .then(() => console.log('資料庫連接成功')) 7 // 連接失敗 8 .catch(err => console.log(err, '資料庫連接失敗')); 9 10 // 創建集合規則 11 const userSchema = new mongoose.Schema({ 12 name: String, 13 age: Number, 14 email: String, 15 password: String, 16 hobbies: [String] 17 }); 18 19 // 使用規則創建集合 20 const User = mongoose.model('User', userSchema); 21 22 //查詢 23 //查詢用戶集合中所有檔案 24 // User.find().then(result =>console.log(result)); 25 26 //find也可以根據條件查詢 27 // User.find({_id:'5f9f997b3550fbb052d377bc'}).then(result =>console.log(result)); 28 29 //findOne方法回傳一條檔案,如果不給條件回傳當前集合中第一條檔案 30 // User.findOne({name:'張三'}).then(result =>console.log(result)); 31 32 //查詢年齡大于20并且小于560的檔案的所有資訊 33 // User.find({age: {$gt:20 , $lt:60}}).then(result =>console.log(result)); 34 35 //查詢hobbies欄位包含吃飯的檔案的所有資訊 36 // User.find({hobbies:{$in:['吃飯']}}).then(result =>console.log(result)); 37 38 //查詢欄位name email 多個欄位已空格 隔開 去掉ID前面加上- 39 // User.find().select('name email -_id').then(result =>console.log(result)); 40 41 //將資料按照年齡進行排序(升序) 42 // User.find().sort('age').then(result =>console.log(result)); 43 //將資料按照年齡進行排序(倒序) 44 // User.find().sort('-age').then(result =>console.log(result)); 45 46 //跳過前兩個查詢后三個 47 // User.find().skip(2).limit(3).then(result =>console.log(result)); 48 49 50 51 //洗掉 52 //洗掉ID為5f9f997b3550fbb052d377be的資訊 53 // User.findOneAndDelete({_id: '5f9f997b3550fbb052d377be'}).then(result =>console.log(result)); 54 55 //洗掉User中所有檔案 56 // User.deleteMany({}).then(result =>console.log(result)); 57 58 //更新 59 60 //王二麻子改成徐鐵皮 61 // User.updateOne({name:'王二麻子'},{name:'徐鐵皮'}).then(result =>console.log(result)); 62 63 //更新所有檔案age改為18 64 // User.updateMany({},{age: 18}).then(result =>console.log(result));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/199693.html
標籤:其他
上一篇:GPS時間同步系統(GPS對時系統)為何是電力必備品
下一篇:Java開發文章匯總(一)
