MongoDB - 基础语句
- 查询语句
1.1 查询数据库
show dbs
1.2 查询表
show collections
1.3 查询某个表全部内容(通过it进行翻页)
db.imooc_collection.find()
db.imooc2.find({m:{$exists:true}})
-
数据库
2.1 use imooc2.1 use imooc (如果没有则自定创建)
2.2 删除当前数据库
db.dropDatabase() -
插入
3.1 插入一条记录(自动创建表)
db.imooc_collection.insert({x:1})
3.2 插入一条记录(自动创建表)
db.imooc_collection.insert({x:2,y:1})
3.3 循环插入数据
for(int i=4;i++;i<100)db.imooc_collection.insert({x:i})
3.4 查看记录数
db.imooc_collection.find().count() -
更新
4.1 更新指定数据(一次更新一条数据)
db.imooc_collection.update({x:2},{x:3})
4.2 批量更新
db.imooc_collection.update({x:2},{$set:{x:3}},false,true)
4.3 更新数据的部分内容(使用{$set:{被更新内容}}操作符)
db.imooc_collection.update({x:2},{$set:{x:3}})
4.4 更新没有的记录,使用“true”,创建数据
db.imooc_collection.update({x:2},{x:4},true) -
删除
5.1 删除表
db.imooc_collection.drop()
5.2 删除数据
db.imooc_collection.remove(args)
不加参数提示以下错误信息:2019-02-07T18:24:50.106+0800 E QUERY [thread1] Error: remove needs a query :
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:409:1
DBCollection.prototype.remove@src/mongo/shell/collection.js:434:18
@(shell):1:1 -
索引
6.1 查看集合的索引:getIndexes()db.imooc_collection.getIndexes()
[
{
“v” : 2,
“key” : {
“_id” : 1
},
“name” : “id”,
“ns” : “imooc.imooc_collection”
}
]
6.2 创建索引
db.imooc_collection.ensureIndex({x:1})