参考官方文档(图文并茂很是好看):Getting Started - MongoDB Documentation正则表达式
MongoDB的查询功能很是强大,同时有些地方也会有点复杂。因此须要下点功夫学习和操练才能用好。mongodb
当咱们进入Mongo Shell
客户端后,其实是进入了一个Javascript语言
的交互环境。
也就是说,MongoDB中的不少命令,尤为是包括定义函数等高级命令,实际上都是Javascript语言,甚至说能够是jQuery
。
了解了这点,一些高级命令如Aggregation学起来就会放松不少。函数
官方说明:学习
:
等于$lt
: Less Than$gt
: Greater Than$gte
: Greater Than or Equal$ne
: Not Equal# age大于等于18 db.mycollection1.find( { age:{$gt: 18} } )
$and
$or
db.mycollection1.find( { $or: [ { age: {$gte: 20} }, { salary: {$gt: 5000} }, { job: "HR" } ] } )
$in
$nin
: Not Indb.mycollection1.find( { age: { $in: [10, 20, 30] } } )
有两种方法:this
/表达式内容/
{$regex: "表达式内容"}
db.mycollection1.find( { name: /^Ja\w+$/ } ) # 或 db.mycollection1.find( { name: { $regex: "/^Jaso\w?$" } } )
# 限定显示条数 db.mycollection1.find().limit(数量) # 跳过指定第几条数据 db.mycollection1.find().skip(2) # 混合使用 db.mycollection1.find().limit(10).skip(3)
自定义查询是指使用自定义函数,格式为$where: function(){...}
spa
db.mycollection1.find( { $where: function() { return this.age >= 18; } } )
即搜索的返回值中,只显示指定的某些字段。字段指为0的不现实,指为1的显示,默认为1。3d
# 格式为: db.mycollection1.find( {查询条件}, {显示与否的选项} ) # 如: db.mycollection1.find( {}, { _id: 0, name: 1, age: 1 } )
能够按指定的某些字段排序,字段标记为1的为Asc升序,标记为-1的为Desc降序。code
db.mycollection1.find().sort({ name:1, age:-1 })
使用count()函数。blog
db.mycollection1.find().count() db.mycollection1.count( {查询条件} )
使用distinct()函数。排序
# 格式为: db.集合名.distinct( "指定字段", {查询条件} ) # 如 db.mycollection1.distinct( "job", { age: {$lt: 40} } )
Aggregation是MongoDB特有的一种Pipline管道型、聚合查询方式。语法稍微复杂一些。
聚合管道能够达到多步骤的分组、筛选功能。这个管道中的每个步骤,成为一个stage
。
经常使用的管道有:
$match
:简单的根据条件过滤筛选$group
:将数据分组,通常配合一些统计函数,如$sum
。$project
:修改document的结构。如增删改,或建立计算结果$lookup
:$unwind
:将List列表类型的Document进行拆分$sort
$limit
$skip
语法格式为:
db.集合名.aggregate( [ {管道表达式1}, {管道表达式2}, {管道表达式2} ] )
示例:
db.Orders.aggregate( [ {$match: { status: "A" } }, {$group: { _id: "$cut_id", total: { $sum: "$amount" } } } ] )