NoSQL专题
MongoDB安装使用教程
根据MingoDB的site安装。然后启动 mongod.exe(windows) ,端口27017 。启动 mongo.exe 开启一个shell.
在linux下启动命令:
$ /usr/lib/mongodb/2.3.2/bin/mongod --port 27001 --fork --dbpath /data/db/2.3.2 --logpath /data/db/2.3.2/mongod.log
创建一个管理用户:
> use admin
> db.addUser('mongouser','mongopass')
重启:
$ sudo kill -15 $(ps -ef | grep mongo | grep -v grep | cut -f8 -d' ')
$ /usr/lib/mongodb/2.3.2/bin/mongod --port 27001 --fork --auth --dbpath /data/db/2.3.2 --logpath /data/db/2.3.2/mongod.log
授权给admin:
> use admin
switched to db admin
> db.aut('mongouser','mongopass')
Thu Jan 31 13:53:31.271 javascript execution failed (shell):1 TypeError: Property 'aut' of object admin is not a function
创建数据库company:
use company
查看数据库:
show dbs;
保存数据:
employee = {name : 'A', no : 1}
db.employees.save(employee)
保存到employees集合。
查看集合:
db.users.find();
下面看看用Java来操作:
public class MongoDBClient {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo('localhost', 27017);
DB db = mongo.getDB('company');
DBCollection collection = db.getCollection('employees');
BasicDBObject employee = new BasicDBObject();
employee.put('name', 'Hannah');
employee.put('no', 2);
collection.insert(employee);
BasicDBObject searchEmployee = new BasicDBObject();
searchEmployee.put('no', 2);
DBCursor cursor = collection.find(searchEmployee);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println('The Search Query has Executed!');
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出:{ '_id' : { '$oid' : '4fec74dc907cbe9445fd2d70'} , 'name' : 'Hannah' , 'no' : 2}
The Search Query has Executed!
Morphia ,是一个Java对象和MongoDB转换工具,适合有JPA /ORM经验的程序员
Map/reduce
在shell中新增准备数据:
> book1 = {name : "Understanding JAVA", pages : 100}
> book2 = {name : "Understanding JSON", pages : 200}
> db.books.save(book1)
> db.books.save(book2)
> book = {name : "Understanding XML", pages : 300}
> db.books.save(book)
> book = {name : "Understanding Web Services", pages : 400}
> db.books.save(book)
> book = {name : "Understanding Axis2", pages : 150}
> db.books.save(book)
写一个Map功能:
> var map = function() {
var category;
if ( this.pages >= 250 )
category = 'Big Books';
else
category = "Small Books";
emit(category, {name: this.name});
};
下面是产生的结果:
{"Big Books",[{name: "Understanding XML"}, {name : "Understanding Web Services"}]);
{"Small Books",[{name: "Understanding JAVA"}, {name : "Understanding JSON"},{name: "Understanding Axis2"}]);
写一个reduce功能:
> var reduce = function(key, values) {
var sum = 0;
values.forEach(function(doc) {
sum += 1;
});
return {books: sum};
};
针对这个集合运行mapreduce:
> var count = db.books.mapReduce(map, reduce, {out: "book_results"});
> db[count.result].find()
{ "_id" : "Big Books", "value" : { "books" : 2 } }
{ "_id" : "Small Books", "value" : { "books" : 3 } }
结果是2 Big Books和 3 Small Books