日期:2014-05-16  浏览次数:20545 次

mongo笔记
db.users.find({$where:function(){return this.age > 30 && this.age < 35;}})


db.users.find({$or:[{name:"mrj6"}, {name:"mrj9"}]})

// 查询
db.users.find({age:{$lt:30}})
db.users.find({$or:[{$where:function(){return this.age > 30 && this.age < 35;}}, {name:"mrj6"}]})


db.users.find({$or:[{$where:function(){return this.age > 30 && this.age < 35;}}, {name:"mrj6"}]}).sort({age:1})		// 1升序,-1降序



db.users.save({ "_id" : ObjectId("5020a0a2f23c9896b393e7dd"), "name" : "mrj0", "age" : 20 })	// updates if exists; inserts if new



db.users.update({name:"mrj0"}, {$inc:{age:69}})
$inc:increments,增加(for numbers only)
$set:sets field to value.
$unset:Deletes a given field.
$push/$pushAll:push array
$addToSet:Adds value to the array
$pop:removes the last element in an array
$pull:removes all occurrences of value from field
$pullAll:removes all occurrences of each value in value_array from field
$rename:	



索引
db.users.ensureIndex({name:1}, {unique:true})	// 唯一索引

db.dropDatabase()	// 删除数据库
db.users.drop()		// 删除表

用户/安全
db.addUser("user1", "123456")	// 添加用户,可以指定向哪个库添加用户,可以指定用户是否只读,第三个参数为true表示只读
db.system.users.remove({user:"user1"})	// 删除用户
如果要启用权限管理,需要在启动时:mongod --auth



db.user.remove()		// 删除记录
db.user.save({name:"mrj", pass:"123456",alias:[{type:"mail",name:"mrjeye"},{type:"qq", name:"8423525"}]})	// 添加记录
db.user.find().forEach(printjson)		// 查询并打印
db.user.find({},{mail:0}).forEach(printjson)	// 查询指定列
db.user.update({name:"mrj"},{$push:{alias:{type:"mobile",name:"13111111111"}}})	// 更新添加指定列数据


db.user.find({alias:{$exists:true}},{'alias.type':true,'alias.name':true}).limit(2).forEach(
	function(collections){
		var collection = collections.alias;

		for(var idx in collection){
			var alias = collection[idx];
			print('The type is:' + alias.type + ', value is:' + alias.name + '\n');
		}
	}
);

db.user.find({alias:{$exists:true}},{'alias.type':true,'alias.name':true}).forEach(function(alias){foreach(var alia in alias){print('type(' + alias[0] + '),value(' + alias.name + ')\n');})})

db.user.find({alias:{$exists:true}},{'alias.type':true,'alias.name':true}).forEach(
	function(alias){
		alias.forEach(
			function(alia){
				print('type(' + alias[0] + '),value(' + alias.name + ')\n');
			}
		)
	}
)

?

?

?

备份:

?

mongodump -h host:port -ddbname -o path -u user -p pass

?

?

还原:

mongorestore -h host:port -d dbname --directoryperdb dbdirectory -u user -p pass --drop

?

?

?

?

?