2.4. MongoDB Shell

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介:

2.4.1. show 查看命令

2.4.1.1. show dbs

show dbs show database names

			
> show dbs
local	(empty)
logging	0.203125GB
test	0.203125GB
			
			

2.4.1.2. show collections

show collections show collections in current database

			

> show collections
bios
system.indexes
			
			

另一种用法是show tables

			
> show tables
bios
system.indexes
			
			

2.4.1.3. show users

show users show users in current database

			

			
			

2.4.1.4. show profile

show profile show most recent system.profile entries with time >= 1ms

			
> show profile
db.system.profile is empty
Use db.setProfilingLevel(2) will enable profiling
Use db.system.profile.find() to show raw profile entries
			
			

2.4.2. 切换数据库

		
use <db name>                set curent database to <db name>

> use logging
switched to db logging
		
		

2.4.3. save

存储嵌套的对象

		
db.foo.save({'name':'neo','address':{'city':'shenzhen','post':518000},'phone':[13113668890,13322993040]})
		
		

存储数组对象

		
db.foo.save({'Uid':'netkiller@msn.com','phone':['13322993040','13113668890']})
		
		

2.4.4. insert

		
db.bios.insert(
   {
     _id: 1,
     name: { first: 'John', last: 'Backus' },
     birth: new Date('Dec 03, 1924'),
     death: new Date('Mar 17, 2007'),
     contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
     awards: [
               {
                 award: 'W.W. McDowell Award',
                 year: 1967,
                 by: 'IEEE Computer Society'
               },
               {
                 award: 'National Medal of Science',
                 year: 1975,
                 by: 'National Science Foundation'
               },
               {
                 award: 'Turing Award',
                 year: 1977,
                 by: 'ACM'
               },
               {
                 award: 'Draper Prize',
                 year: 1993,
                 by: 'National Academy of Engineering'
               }
             ]
   }
)
		
		

2.4.5. update

根据query条件修改,如果不存在则插入,允许修改多条记录

db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
		

2.4.6. remove

删除uid=10的记录

		
db.foo.remove({'uid':10})
		
		

删除所有的记录

db.foo.remove()
		

2.4.6.1. 删除条件使用 _id

db.foo.remove({ "_id" : ObjectId("56e10b66a22ef1b1408b4567")})
			

2.4.7. 删除 collection

db.collection.drop()
		

2.4.8. count()

		
> db.access.count()
51528
> db.access.count()
104401
		
		

2.4.9. group()

group()类似SQL中的Group by

		
> db.test.group({key: {remote_addr: true}, initial: {count: 0}, reduce: function(obj, prev) {prev.count++}});
[
	{
		"remote_addr" : "192.168.2.76",
		"count" : 3
	},
	{
		"remote_addr" : "192.168.2.70",
		"count" : 1
	}
]
		
		

2.4.10. find() MongoDB 2.x

查找所有 所有记录

db.foo.find()                list objects in collection foo
db.foo.find( { a : 1 } )     list objects in foo where a == 1
		

查找一条记录

db.foo.findOne()
		

根据条件检索10条记录

db.foo.find({'name':'neo'}).limit(10)
		

sort排序

db.foo.find({'name':'neo'}).sort({'Dt',-1})
db.foo.find().sort({'Ct':-1}).limit(1)
		

count记录统计操作

db.foo.count()
		

distinct操作,去重复查询指定列,

db.foo.distinct('name')
		

”>=”操作

		
db.foo.find({"timestamp": {"$gte" : 2}})
		
		

子对象的查找

db.foo.find({'address.city':'shenzhen'})
		

2.4.11. find() MongoDB 3.x

db.getCollection('tracker').find({name:"81004892"})
	

2.4.11.1. Query

2.4.11.2. 包含字段

		
db.getCollection('pyramidSelling').find({},{'phone':1})			
		
		

2.4.11.3. 排除字段

db.getCollection('pyramidSelling').find({},{'phone':0})			
		

2.4.11.4. sort()

db.getCollection('tracker').find({name:"81004892"}).sort({ctime: -1})
		

2.4.12. 管道操作

		
cat data.bson | mongo test
		
		

2.4.13. shutdownServer

关闭MongoDB数据库

		
db.shutdownServer()
		
		

2.4.14. aggregate

2.4.14.1. project

2.4.14.1.1. $split
{
    "_id" : ObjectId("591a710320156761bdf68a06"),
    "_class" : "mis.domain.PyramidSelling",

	...
	...

    "status" : true,
    "createdDate" : ISODate("2017-05-16T03:24:51.511Z")
}			
				
				
db.getCollection('pyramidSelling').aggregate([
  { $project : { _class : { $split: ["$_class", "."] } } }
]);			
				
				
2.4.14.1.2. substr
db.getCollection('pyramidSelling').aggregate(
   [
      {
         $project: {
            userName: 1,
            phone: {
               prefix: { $substr: [ "$phone", 0, 3 ] },
               mobile: { $substr: [ "$phone", 3, 11 ] }
            },
         }
      }
   ]
)				
				

2.4.14.2. groupby + sum

select username, sum(balance) as total from users group by member.

			
db.member.aggregate([{ 
    $group: { 
        _id: "$username", 
        total: { $sum: "$balance" }
    } 
}])
			
	





原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
4月前
|
存储 JSON 分布式计算
MongoDB【部署 01】mongodb最新版本6.0.5安装部署配置使用及mongodb-shell1.8.0安装使用(云盘分享安装文件)
MongoDB【部署 01】mongodb最新版本6.0.5安装部署配置使用及mongodb-shell1.8.0安装使用(云盘分享安装文件)
149 0
|
3月前
|
NoSQL Shell MongoDB
MongoDB Shell工具:mongosh的使用
MongoDB Shell工具:mongosh的使用
146 0
|
NoSQL 关系型数据库 MySQL
MongoDB Shell操作(二)
MongoDB Shell操作(二)
135 0
|
NoSQL Shell MongoDB
MongoDB Shell操作(一)
MongoDB Shell操作(一)
128 0
MongoDB Shell操作(一)
|
NoSQL Shell MongoDB
MongoDB后台shell语句(二)
MongoDB后台shell语句(二)
|
SQL NoSQL Shell
MongoDB后台shell语句(一)
MongoDB后台shell语句(一)
|
NoSQL Shell 数据库
MongoDB通过Shell 实现集合的日常归档
MongoDB通过Shell 实现集合的日常归档 1.MongoDB数据归档的意义和其他类型的数据库一样,归档对MongoDB同样重要。通过归档,可以保持集合中合适的数据量,对数据库的性能是一种保障,也就是大家常说的数据冷热分离。
1939 0
|
JSON NoSQL Shell
《MongoDB极简教程》第二章 MongoDB 基本命令(Shell)
MongoDB的所有请求都以命令的形式发出,支持的命令列表参考Database Commands The mongo Shell:https://docs.mongodb.com/manual/mongo/ db是mongoDB的全局变量,持有当前数据库schema的引用。
1089 0