# 主键查询
## 使用主键查询时需要使用 ObjectId() 函数对传入的主键进行修饰才可以进行查询
db.user.find({
'_id':ObjectId("636e1a73289d1b3a66bf489c")
})
# 查询指定字段或忽略指定字段
## 第二个大括号决定查询哪些字段,1为显示,除 _id 外其他字段均为默认不显示
## 所以若不需要 _id 字段请使用 _id:0
## sql: select id,name,age from table
## mongo:
db.table.find(
{
},{
_id:0,
name:1,
age:1
}
)
# 查询指定字段等于某值 =
## sql: select * from table where id = 100
## mongo:
db.table.find({
id:100
})
# 查询指定字段大于某值 >
## sql: select * from table where age > 12
## mongo:
db.table.find({
age:{
$gt:12
}
})
# 查询指定字段小于等于某值 <
## sql: select * from table where age <= 60
## mongo:
db.table.find({
age:{
$lte:60
}
})
# 查询指定区间 between and
## sql: select * from table where age between 20 and 80
## mongo:
db.table.find({
age:{
$gte:20,
$lte:80
}
})
# 查询指定区间外 or
## sql:
select * from table where age < 18 or age > 80
## mongo:
db.table.find({
$or:[
{age:{$lt:18}},
{age:{$gt:80}}
]
})
# and查询 and
## sql: select * from user where sex = 1 and age > 10
## mongo:
db.user.find({
'sex':1,
'age':{'$gt':10}
})
# 指定集合 in
## sql: select * from user where id in (1,2,3,5);
## mongo:
db.user.find({
'id':{$in:[1,2,3,4,5]}
})
# 指定集合外 not in
## sql: select * from user where id not in (1,2,3)
## mongo:
db.user.find({
'id':{'$nin':[1,2,3]}
})
# 模糊查询 %like%
## sql: select name,age from user where name like "%程%"
## mongo:
db.user.find(
{
name:/程/
## 或使用 'name':{'$regex':/程/}
},{
_id:0,
name:1,
age:1
}
)
# 模糊查询,头部匹配 like%
## sql: select * from user where name like "程%"
## mongo:
db.user.find({
name:/^程/
})
# 模糊查询,尾部匹配 %like
## sql: select * from user where name like "%程"
## mongo:
db.user.find({
name:/程$/
})
# 查询总数 count()
## sql:select count(id) from user where age > 18
## mongo:
db.user.find({ ## 或使用 db.user.count({'age':{'$gt':18}})
'age':{'$gt':18}
}).count()
# 排序 order by
## sql: select * from user order by id desc
## mongo: (升序:1,降序:-1)
db.user.find().sort({'id':-1})
# 分页 limit
## sql: select * from user limit 20,10
## mongo:
db.user.find().skip(20).limit(10)
# 去重统计
## sql: select * fr
## mongo:
db.user.distinct(
'name', ## 去重依据字段
{'age':{'$gte':15}}, ## 筛选条件
{'_id':0} ## 不需要显示的列
)
表达式操作符
常用表达式
含义
$sum
计算总和,{KaTeX parse error: Expected 'EOF', got '}' at position 7: sum: 1}̲表示返回总和×1的值(即总和的…sum: ‘$制定字段’}也能直接获取制定字段的值的总和
# 删除指定条件
## sql: delete from user where name = 'bilibili'
## mongo:
db.user.remove({
'name':'bilibili'
})
# 删除所有
## sql: delete from user
## mongo:
db.user.remove()