mongodb基本指令

创建表

use指定,后面是表的名称

use mydb
创建集合

db.xxx.insert(json)
db指令后面参数为集合的名称,insert函数创建这个集合,后面跟json数据

db.user.insert({"username":"zhangsan", "age": 20})
查询表

show dbs
删除某表下的集合

db.xxx.drop()
删除某个表

db.dropDatabase()
查询某个集合

使用use指令指向一个表,在这个表中执行

// 查询这个表下面的所有集合
show collections

// xxx表示要查询这个集合下的所有列
db.xxxx.find()
过滤到name中相同的数据

db.user.distinct("name")

// 相当于 select distinct name from user;
查询条件查询

查询年龄等于23 的数据
db.xxxx.find({age: 23})
年龄大于22的数据
db.xxxx.find({age: {$gt:22}})
年龄小于22的数据
db.xxxx.find({age: {$lt:22}})
年龄大于等于的22的数据
db.xxxx.find({age: {$gte:22}})

// 小于等于22
db.xxxx.find({age: {$lte:22}})

// 查询大于等于22 并且 小于等于26
db.xxxx.find({age: {$gte:23, $lte:26}})
查询name中包含mongo的数据 模糊查询用于搜索
db.xxxx.find({name:/mongo/})

// 相当于 %%
select *from user where name like '%mongo%'

// 查询name中以mongo开头的
db.xxxx.find({name: /^mongo/})
// 相当于
select *from user where name like 'mongo%'

结尾就在后面加个$符号
指定列查询显示,find()第二个参数显示,
// 只显示name
db.xxxx.find({}, {name:1})

// 显示name个age
db.xxxx.find({}, {name:1, age:1})
排序 sort() 1表示升序,-1表示降序

db.xxxx.find().sort({age:1})

db.xxxx.find().sor({age:-1})
查询限制数量的数据

// 查询前5条数据
db.xxxx.find().limit(5)

查询前10条以后的数据
db.xxxx.find().skip(10)

猜你喜欢

转载自www.cnblogs.com/zhouyang9527/p/12747175.html
今日推荐