基本概念
常用命令
MongoDB使用BSON來存儲數(shù)據(jù)和網(wǎng)絡數(shù)據(jù)交換。
MongoDB操作的都是對象谒兄。
增
#創(chuàng)建數(shù)據(jù)庫
//創(chuàng)建完必須存數(shù)據(jù)独令,數(shù)據(jù)庫才會存在
use demo
#創(chuàng)建集合
//相當于表
db.createCollection("user")
#向集合中插入數(shù)據(jù)
//db為當前數(shù)據(jù)庫,沒有指定數(shù)據(jù)庫的話端朵,會默認創(chuàng)建一個test數(shù)據(jù)庫
//user為collection,如果集合不存在,相當于創(chuàng)建集合+插入數(shù)據(jù)兩個動作
db.user.insert({userId:101,userName:'olivia',userAge:22,school:{name:'WHU',location:'wuhan'}})
#導入文檔
>mongoimport -d db_name -c collection_name --file file_path
查
#查看所有數(shù)據(jù)庫
show dbs
#查看當前數(shù)據(jù)庫中所有的集合
show collections
#查看集合中所有的數(shù)據(jù)
db.user.find()
#格式化查看
db.user.find().pretty()
#查看查詢結果中的第一條數(shù)據(jù)
db.user.findOne()
#查看集合中某一條數(shù)據(jù)
//根據(jù)文檔值查詢
db.user.find({userName:"olivia"})
//根據(jù)子文檔值查詢
db.user.find({"school.name":"WHU"})
#條件查詢
//查詢userAge>28的所有數(shù)據(jù)
//$gt:>燃箭,$lt:<冲呢,$eq:=,$gte:>=,$lte:<=
db.user.find({userAge:{$gt:28}})
改
#更新文檔
db.user.update({userName:"olivia"},{$set:{userAge:18}})
#更新子文檔
//鍵名school.name必須加引號
db.user.update({"userName":"olivia"},{$set:{"school.name":"HUST"}})
#數(shù)據(jù)庫重命名
db.copyDatabase('old_name', 'new_name');
use old_name
db.dropDatabase();
刪
#刪除當前數(shù)據(jù)庫
db.dropDatabase()
#刪除當前數(shù)據(jù)庫中的某個集合
db.user.drop()
#刪除某條數(shù)據(jù)
db.user.remove({"userName":"jack"})
Mongoose和MongoDB
schema —— collection
models —— documents