2.mongoDB 命令

1.命令行
	mongo 127.0.0.1:27017  // 连接

	help // 查看帮助

	show dbs //查看数据库

	show tables // 查看有哪些表

	use local // 切换数据库 local

	use test 并插入 db.test.insert({x:1}) // 则建立一个 test 数据库

	db.表名.insert(json 数据) // 往表中插入数据 

	show collections // 查看建立的表名

	db.表名.find() // 查询

	db.test.find({x:1})

	for(i=3;i<100;i++)db.test.insert({x:i})  // 循环插入

	db.test.find().count() // 计数

	db.test.find().skip(3).limit(2).sort({x:1}) // 跳过前3,限制返回2条,按 x 排序

	db.test.update({x:1},{x:99}) // 更新, x:1 => x:99

	db.test.update({c:3}, {$set:{b:100}}) // $set 部分更新,存在即更新,不会更新其他字段

	db.test.update({y:100},{y:999},true) // 如果查找的字段不存在,自动写入

	db.dropDatabase() // 删除当前数据库

	db.test.update({a:1},{$set:{a:100}},false,true) // true, mongodb 默认只更新查找到的第一条,true 的话更新全部

	db.test.remove({a:100}) // 默认删除查找到的全部数据

	db.表名.drop() // 删除表

	db.test.findOne() // 查找一条数据

	db.test2.insert({time:new Date()}) // 插入当前时间

2.索引
	db.test.ensureIndex({x:1}) // 在 x 上创建索引, 1 表示正向索引,-1 负向索引

	db.test.getIndexes() // 获取索引

	db.test2.ensureIndex({x:1,y:1}) // 复合索引

	db.test2.ensureIndex({time:1},{expireAfterSeconds:10}) // 过期索引,10m过期

	db.test2.ensureIndex({"article":"text"}) // 创建全文索引

	db.test2.find({$text:{$search:"aa"}})  // 查找全文索引

	db.test2.find({$text:{$search:"aa oo"}}) // 全文查找 aa 或 oo 

	db.test2.find({$text:{$search:"aa oo -dd"}}) // 全文查找,不包含 dd

	db.test2.find({$text:{$search:"\"aa\" \"bb\" \"cc\""}})  // 全文查找,&& 

	db.test2.find({$text:{$search:"aa bb cc"}},{score:{$meta:"textScore"}}) // 返回分值
	db.test2.find({$text:{$search:"aa bb cc"}},{score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}}) // 按分值排序

	db.test3.ensureIndex({x:1, y:1, z:1,a:1},{name:"test_index_name"}) // 给索引起名字

	db.test3.dropIndex("test_index_name") // 删除索引

	 db.test3.ensureIndex({m:1, n:1}, {unique:true}) // 唯一索引

	 db.test.find({m:{$exists:true}}) // 只查找 m 存在的字段

	 db.test.ensureIndex({m:1},{sparse:true}) // 创建稀疏索引

	 db.test.find({m:{$exists:false}}) // 在稀疏索引上查找这个字段不存在的记录,会返回

	 db.test.find({m:{$exists:false}}).hint("m_1") // 强制使用 索引 m_1

	 db.test.ensureIndex({w:"2d"}) // 创建 2d 索引

	 db.test.insert({w:[180,80]}) // 插入 2d 索引

	 db.test.find({w:{$near:[1,1]}}) // 2d 查询,默认返回100个距离查询点最近的点

	 db.test.find({w:{$near:[1,1], $maxDistance:10}}) // 限制距离,10

	 db.test.find({w:{$geoWithin:{$box:[[0,0],[3,3]]}}}) // 查找位于某个矩形中的点

	 db.test.find({w:{$geoWithin:{$center:[ [0,0],5 ]}}}) // 查找圆中的点

	 db.test.find({w:{$geoWithin:{$polygon:[ [0,0], [0,1], [2,5], [6,1] ]}}}) // 查找多边形中的点

	 db.runCommand({geoNear:"表名",near:[1,2], maxDistance:10, num:1}) 

	 db.system.profile.find().sort({$natural:-1}).limit(1)

	 db.getProfilingLevel() 
	 db.setProfilingLevel(0)
	 db.getProfilingStatus()

	 db.test.find({x:1}).explain() 

3.安全
	auth = true // 开启权限认证

	db.createUser({user:"test", pwd:"123456", roles:[ {role:"userAdmin", db:"admin"}, {role:"read", db:"test"} ]}) // 创建用户
	 mongo 127.0.0.1:27017 -u test -p // 重新登录



猜你喜欢

转载自blog.csdn.net/enlyhua/article/details/83048439