studyNotes icon indicating copy to clipboard operation
studyNotes copied to clipboard

MongoDB基本用法

Open junhey opened this issue 7 years ago • 0 comments

官方文档:https://docs.mongodb.com/getting-started/shell/

Homebrew安装mongodb

brew update
brew install mongodb

默认的安装路径:

The databases are stored in the /usr/local/var/mongodb/ directory  
The mongod.conf file is here: /usr/local/etc/mongod.conf   
The mongo logs can be found at /usr/local/var/log/mongodb/  
The mongo binaries are here: /usr/local/Cellar/mongodb/[version]/bin  

启动

mongod --config /usr/local/etc/mongod.conf
# 或者
mongod --config /usr/local/etc/mongod.conf --fork

其中mongod.conf内容如下:

systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  bindIp: 127.0.0.1

直接输入mongo或者下面的过程:

cd /usr/local/bin //进入数据库目录
./mongo //连结数据数据库
show dbs //列出数据库
use school //切换到school数据库,如果没有此数据库则创建此数据库

#增加

// 创建一个student集合,并且插入一个数据。
db.student.insert({"age":20, "name":"xiaoming", "sex":"man", "score":{"yuwen":100, "shuxue":70}});

#查询
//查询 当前集合
show collections
//查询:student
db.student.find()
//查询:年龄12
db.student.find({"age":12})
//查询:数学 70
db.student.find({"score.shuxue":70})
//查询:数学大于60分
db.student.find({"score.shuxue":{$gt:60}})
//查询:有数学成绩这个字段
db.student.find({"score.shuxue":{$exists:true}})
//查询:数学成绩为70并且语文为100
db.student.find({"score.shuxue":70,"score.yuwen":100})
//查询:语文100或者语文90
db.student.find({$or:[{"score.yuwen":100},{"score.yuwen":90}]})
//查询:name中包含'e'的数据
 db.student.find({name:/e/});
//:查询以a打头的数据
db.student.find({name:/^a/});
//查询:一个
db.student.findOne();
# 排序 sort  1:升序(小的在上)  -1:降序(大的在上)
//查询后排序:语文成绩降序,如果语文成绩相等则年龄生序
db.student.find().sort({"score.yuwen":-1,"age":1})
# limit和skip
//查询:限制返回一个结果
db.student.find().limit(1)
// 查询:跳过一条数据
db.student.find().skip(1);

#修改
//完整替换,student 修改成 age:10
db.student.update({"score.shuxue":70},{"age":10})
//查询数学分数为70的一个人:年龄修改为10.
db.student.update({"score.shuxue":70},{$set:{"age":10}})
//查询所有 数学分数为70:年龄修改为10.
db.student.update({"score.shuxue":70},{$set:{"age":10}},{multi : true})
//查询小红,修改当前lastModified为当前时间
db.student.update({ "name" : "xiaohong" },{$currentDate: { "lastModified": true } })

#删除
//删除:文档,没有确认,慎用
db.student.dropDatabase()
//删除:全部名字为xiaohong
db.student.remove({"name":"xiaohong"});
//删除:一个名字为xiaohong
db.student.remove({"name":"xiaohong",{justOne:true}});

junhey avatar Apr 30 '18 02:04 junhey