33.3. MongoDB Shell

33.3.1. show 查看命令

33.3.1.1. show dbs

show dbs show database names

			
> show dbs
local	(empty)
logging	0.203125GB
test	0.203125GB
			
			
33.3.1.2. show collections

show collections show collections in current database

			

> show collections
bios
system.indexes
			
			

另一种用法是show tables

			
> show tables
bios
system.indexes
			
			
33.3.1.3. show users

show users show users in current database

			

			
			
33.3.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
			
			

33.3.2. 切换数据库

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

> use logging
switched to db logging
		
		

33.3.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']})
		
		

33.3.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'
               }
             ]
   }
)
		
		

33.3.5. update

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

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

33.3.6. remove

删除uid=10的记录

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

删除所有的记录

db.foo.remove()
		
33.3.6.1. 删除条件使用 _id
db.foo.remove({ "_id" : ObjectId("56e10b66a22ef1b1408b4567")})
			

33.3.7. 删除 collection

db.collection.drop()
		

33.3.8. count()

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

33.3.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
	}
]
		
		

33.3.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'})
		

33.3.11. find() MongoDB 3.x

db.getCollection('tracker').find({name:"81004892"})
	
33.3.11.1. Query
33.3.11.2. 包含字段
		
db.getCollection('pyramidSelling').find({},{'phone':1})			
		
		
33.3.11.3. 排除字段
db.getCollection('pyramidSelling').find({},{'phone':0})			
		
33.3.11.4. sort()

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

33.3.12. 管道操作

		
cat data.bson | mongo test
		
		

33.3.13. shutdownServer

关闭MongoDB数据库

		
db.shutdownServer()
		
		

33.3.14. aggregate

33.3.14.1. project
33.3.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", "."] } } }
]);			
				
				
33.3.14.1.2. substr
db.getCollection('pyramidSelling').aggregate(
   [
      {
         $project: {
            userName: 1,
            phone: {
               prefix: { $substr: [ "$phone", 0, 3 ] },
               mobile: { $substr: [ "$phone", 3, 11 ] }
            },
         }
      }
   ]
)				
				
33.3.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 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

项目突然跑不起来报这个错 Exception in monitor thread while connecting to server 10.18.21.79:27117 com.mongodb.MongoSocketReadException: Exception receiving message at com.mongodb.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:536) at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:421) at com.mongodb.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:290) at com.mongodb.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255) at com.mongodb.connection.CommandHelper.sendAndReceive(CommandHelper.java:84) at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:34) at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:91) at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:51) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:127) at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) at java.lang.Thread.run(Thread.java:748) Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:210) at java.net.SocketInputStream.read(SocketInputStream.java:141) at com.mongodb.connection.SocketStream.read(SocketStream.java:84) at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:547) at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:418)
最新发布
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值