版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunshine_YG/article/details/83927252
服务端启动
./mongod [--dbpath=/data/db]
/data/db mongo默认数据库位置
客户端连接
./mongo ip:port/dbname -u user -p password
数据库操作:
登录后默认数据库test
显示数据库列表
show dbs
创建/切换 数据库
use dbname
查看当前数据库
db
删除当前所选数据库
db.dropdatabase
增删改查:
插入
db.collectionName.insert({"key":document});
删除
db.collectionName.remove({"key":document});
更新
//update 只能更新已存在的
db.collectionName.update({"key":document},{"key":new document});
//upsert 存在更新,不存在插入
db.collectionName,update({"key":document},{"key":new document},true);
查询
db.collectionName.find({"key":document});
//返回选择的列,显示col2、col3列
db.collectionName.find({"key":document},{"col1":0,"col2":1,"col3":1});
1、$lt、$lte、$gt、$gte、$ne
lte =less than equal
gte=greater than equal
ne=not equal
// 18<= age <25
db.collectionName.find({"age":{"$gte":18,"$lt":25}});
// 注册时间18年以前的
start=new Date("01/01/2018");
db.collectionName.find({"registerTime":{"$lt":start}});
2、$in、$nin、$or 与mysql中in、not in、or不同的是 值的类型可以不同
//查找name=H2o或age=20的人
//"H2o"与20类型不同
db.collectionName.find({"$or":[{"age":20},{"name":"H2o"}]});
//查找年龄为18、19、20、21、22、23的人
db.collectionName.find({"age":{"$in":[18,19,20,21,22,23]}});
3、$not、$mod 取余
//查找符合 x%5=1 的x 如:1,6,11
db.collectionName.find({"numbers":{"$mod":[5,1]}});
//查找符合 x%5!=1 的x 如:2,3,4,5,7,8,9,10
db.collectionName.find({"numbers":{"$not":{"$mod":[5,1]}}});
4、$exist
//查询到的结果为:sex==null 或者没有 sex字段的记录
db.collectionName.find({"sex":null});
//查询到的结果为:sex==null
db.collectionName.find({"sex":{"$in":[null],"$exist":true}});
5、正则表达式
//查询到 明朝那些事儿1、明朝那些事儿2、明朝那些事儿3等等
db.collectionName.find({"title":/明朝那些事儿?/});
6、数组 $all (全匹配)、$size(数组大小)、$slice(截取)
//arr下有value1与value2才匹配
db.collectionName.find({"arr":{"$all":["value1","value2"]}});
//arr大小为5则匹配
db.collectionName.find({"arr":{"$size":5}});
//查询{"key":document}下的arr的前10个
db.collectionName.find({"key":document},{"arr":{"$slice":10}});
//后10个
db.collectionName.find({"key":document},{"arr":{"$slice":-10}});
7、查询内嵌文档 $elemMatch
//查询key下面的key1=value1且key2>30 的记录
db.collectionName.find({"key":{"$elemeMatch":{"key1":"value1"},{"key2":{"$gt":30}}}});
8、$where(慢:每个文档从BSON转换成JavaScript对象,然后通过$where的表述式来运行)
//查询价格+10==100的记录
//以下两种写法等价
db.collectionName.find({"$where":"this.price+10==100"});
db.collectionName.find({"$where":function(){return this.price+10==100;}});
9、limit、skip、sort
//按price升序排序,跳过前两个,然后取10个。即取第3-12个。
// 1升序 -1降序
db.collectionName.find().skip(2).limit(10).sort({"price":1});
10、
db.collectionName.find({"key":"value"}).sort({"x":1});
//实际上执行时,shell会转化成
db.collectionName.find({"$query":{"key":"value"},"$orderby":{"x":1}});