1. 数据库操作
use 数据库名
: 选择数据库,没有则自动创建show databases
:查看所有数据库db
: 查看当前正在使用哪一个数据库数据库名.dropDatabase()
:删除指定数据库数据库
2. 集合操作
db.createCollection(name)
:显示创建集合- name:要创建的集合名称
show collections
:查看当前库中的所有集合db.集合名.drop()
:删除指定集合
3. 文档操作
3.1 插入
插入单条数据
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
// 示例
db.comment.insert({"articleid":"100000","content":"今天天气真好,阳光明媚","userid":"1001","nickname":"Rose","createdatetime":new Date(),"likenum":NumberInt(10),"state":null})
批量插入
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
3.2 基本查询
db.collection.find(<query>, [projection])
- query: document类型。 查询条件筛选器
- projection:document类型。查询结果列选择器
3.3 更新文档
db.collection.update(query, update, options)
//或
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2
}
)
3.4 删除文档
db.集合名.remove(条件)
3.5 复杂查询
db.collection.count(query, options)
:统计记录数- query:document类型,查询筛选条件
- options:document类型,可选。
db.comment.find().limit(3)
: 限制查询返回条数db.comment.find().skip(4).limit(2)
:分页查询db.comment.find().sort({userid:-1,likenum:1})
:添加排序方式- -1表示倒序,1表示正序
db.comment.find({content:/^专家/})
: 查支持字段正则匹配
db.集合名称.find({ "field" : { $gt: value }}) // 大于: field > value
db.集合名称.find({ "field" : { $lt: value }}) // 小于: field < value
db.集合名称.find({ "field" : { $gte: value }}) // 大于等于: field >= value
db.集合名称.find({ "field" : { $lte: value }}) // 小于等于: field <= value
db.集合名称.find({ "field" : { $ne: value }}) // 不等于: field != value
// 包含查询
db.comment.find({userid:{$in:["1003","1004"]}})
db.comment.find({userid:{$nin:["1003","1004"]}})
db.comment.find({$and:[{条件1},{条件2}]})
: 条件连接查询db.comment.find({$or:[{条件1},{条件2}]})
:条件连接查询
4. 索引
db.collection.getIndexes()
: 查看索引
db.collection.createIndex(keys, options)
:创建索引
db.comment.createIndex({userid:1,nickname:-1})
db.collection.dropIndex(index)
:删除索引
db.collection.find(query,options).explain(options)
:查看查询的执行计划
5. 总结
- 切换数据库:
use db1
- 插入数据:
db.comment.insert({bson数据})
- 查询所有数据:
db.comment.find()
- 条件查询数据:
db.comment.find({条件})
- 查询一条记录:
db.comment.findOne({条件})
- 限制查询条数:
db.comment.find({条件}).limit(条数)
- 跳过查询条数:
db.comment.find({条件}).skip(条数)
- 全局修改数据::
db.comment.update({条件},{修改后的数据})
- 局部修改数据:
db.comment.update({条件},{$set:{要修改部分的字段:数据})
- 将数据字段值自增:
db.comment.update({条件},{$inc:{自增的字段:步进值}})
- 删除数据:
db.comment.remove({条件})
- 统计查询:
db.comment.count({条件})
- 模糊查询:
db.comment.find({字段名:/正则表达式/})
- 条件比较运算:
db.comment.find({字段名:{$gt:值}})
- 包含查询:
db.comment.find({字段名:{$in:[值1,值2]}})
或db.comment.find({字段名:{$nin:[值1,值2]}})
- 条件连接查询:
db.comment.find({$and:[{条件1},{条件2}]})
或db.comment.find({$or:[{条件1},{条件2}]})