行、列的概念。json来存储数据集合相当于表文档相当于行
1.查看数已存在据库
show dbs;
2.创建数据库
use dbname;
如果
dbname已经存在,则会切换到该数据库
如果dbname不存在,则会创建临时数据库,只有在创建集合时,才会真正创建该数据库
3.切换数据库
use dbname;
4.查看当前所在数据库
db;5.删除数据库(需要先切换到要删除的数据库)
db.dropDatabase();
show collections
db.createCollection(collectionName[, options]);
db.collectionName.insert({"name": "jack"})
db.collection.drop();
find()、findOne())1.插入文档(需要指定集合collectionName,然后,插入文档)
db.collectionName.insert({})
1.文档中的数据结构为
json格式
2.每条数据中字段可能不一致
3.每天数中想同的字段值类型也可能不一致
2.查看文档(需要指定集合collectionName,然后,查看文档内容)
db.collectionName.find();
3.查询当前集合根据key去重后的值列表
db.collectionName.distinct('key');
4.查询相等
db.collectionName.find({"name": "lucy"});
4.查询大于
db.collectionName.find({"key": {$gt: number}});
5.查询小于
db.collectionName.find({"key": {$lt: number}});6.查询大于等于
db.collectionName.find({"key": {$gte: number}});7.查询小于等于
db.collectionName.find({"key": {$lte: number}});8.查询大于等于并且小于等于
db.collectionName.find({"key": {$gte: number, $lte: number}});9.查询大于等于或小于等于
db.collectionName.find({$or: [{"key": {$gte: number}}, {"key": {$lte: number}}]});10.查询包含(模糊查询)
db.collectionName.find({"key": /value/});
10.查询以什么开头
db.collectionName.find({"key": /^value/});11.查询以什么结尾
db.collectionName.find({"key": /value$/});12.查询指定列
db.collectionName.find({}, {"key":1});

13.排序(1:升序,-1:降序)
db.collectionName.find().sort({"key": 1});
14.查询前1条数据
db.collectionName.find().limit(1);
15.跳过前1条数据,查询前一条数据(可以用作分页)
db.collectionName.find().skip(1);
16.统计数量
db.collectionName.find().count();update())$set
db.collectionName.update({"key": "value"}, {$set: {"key": "value"}})
db.collectionName.update({"key": "value"}, {"key": "value"})db.collectionName.update({"key": "value"}, {$set: {"newKey": "value"}});
db.collectionName.update({"key": "value"}, {$set: {"newKey": "value"}}, {"multi": true});加法运算,$inc
db.collectionName.update({"key": "value"}, {$inc: {"key": "value"}}, false, true);
remove())db.collectionName.remove({"key": "value"});db.collectionName.remove({"key": "value"}, {justOne: true});
db.collectionName.ensureIndex({"key": 1});db.collectionName.getIndexes();db.collectionName.dropIndex({"name": 1});db.collectionName.ensureIndex({"key": 1}, {"name": "selfIndexName"});db.collectionName.ensureIndex({"name": 1, "age": 1});
db.collectionName.find({"name": "xxx", "age": xx});,可以命中索引
db.collectionName.find({"age": xx, "name": "xxx"});,可以命中索引
db.collectionName.find({"name": "xxx", "otherKey": "xxx"});,可以命中索引
db.collectionName.find({"name": "xxx"});,可以命中索引
db.collectionName.find({"age": xx});,不会命中索引
db.collectionName.ensureIndex({"key": 1}, {"unique": true});排序做索引,如果没有对排序的key设置索引,MongoDB在将所有数据提取到内存并排序时,会导致内存爆满,从而查询失败。db.user.find().explain("executionStats");executionTimeMillisEstimate,单位:毫秒indexBounds: