참조 :  http://nosql.mypopescu.com/post/392418792/translate-sql-to-mongodb-mapreduce
저작자 표시 비영리
신고
Posted by jeonguk





http://dittmarconsulting.wordpress.com/2012/01/26/cloud-foundry-environment/
저작자 표시 비영리
신고
Posted by jeonguk


페이징 처리
일단은 이렇게 구현했는데
더 좋은 방법이 있는가 모르겠네..ㅋㅋ

일단 정리


Controller


@RequestMapping

public String getPostAllWithPages(@RequestParam(value = "pageNum", required = false, defaultValue = "0") int pageNum,

Model model) {

Page<Post> postList = postService.findPostAllwithPages(new PageRequest(pageNum, 10, new Sort("postCreateDate")));


Pager pager = new Pager(postList, 10);


pager.linkPage = "";


model.addAttribute("pager", pager.print());

model.addAttribute("postList", postList.getContent());

return "post/index.do";

}


Service

public Page<Post> findPostAllwithPages(Pageable pageRequest) {
Page<Post> postList = postRepository.findAll(pageRequest);
return postList;
}


Repository
@Repository
public interface PostRepository extends MongoRepository<Post, String> {

@Override
Page<Post> findAll(Pageable pageable);

저작자 표시 비영리
신고
Posted by jeonguk


mongoTemplate를 사용해서 

Post post = new Post();
post.setId();
....
...


 mongoTemplate.insert(post,"Post");

collection name을 예를 들어 대문자를 포함해서 컬렉션 네임을 Post 로 생성할 경우

spring mvc , mongoRepository에서 findBy.. 로 값을 못가져 온다.

컬렉션 명을 소문자로 (post) 만드니 제대로 가져온다.

써놓고 보니 뭔소리인지 모르겟네.ㅋㅋ

post 컬렉션에 userEmail이라는 컬럼?? 이 있고

mongoRepository 인터페이스 를 extends 한 PostRepository 에서 

List<Post> findByUserEmail(userEmail);  로 값으 가져올때 값을 가져오지 못한다. (에러도 안나고)

컬렉션 네임을 소문자로 생성하자.


 

 
 
저작자 표시 비영리
신고
Posted by jeonguk

Cheat MongoDB

Database/MongoDB 2012.02.17 12:37 |


CONSOLE COMMANDS

help show all the console commands (same as this section) show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries with time >= 1ms use <db name> set curent database to <db name> db.help() help on DB methods db.foo.help() help on collection methods db.foo.find() list objects in collection foo db.foo.find({a:1}) list objects in foo where a == 1 it result of last line evaluated; use to further iterate

DATABASE METHODS

db.addUser(username, password) db.auth(username, password) db.cloneDatabase(fromhost) db.commandHelp(name) // returns the help for the command db.copyDatabase(fromdb, todb, fromhost) db.createCollection(name, { size : ..., capped : ..., max : ... } ) db.currentOp() // displays the current operation in the db db.dropDatabase() db.eval(func, args) // run code server-side db.getCollection(cname) // same as db['cname'] or db.cname db.getCollectionNames() db.getLastError() // just returns the err msg string db.getLastErrorObj() // return full status object db.getMongo() // get the server connection object db.getMongo().setSlaveOk() // allow this connection to read from the nonmaster member of a replica pair db.getName() db.getPrevError() db.getProfilingLevel() db.getReplicationInfo() db.getSisterDB(name) // get the db at the same server as this onew db.killOp() // kills the current operation in the db db.printCollectionStats() db.printReplicationInfo() db.printSlaveReplicationInfo() db.printShardingStatus() db.removeUser(username) db.repairDatabase() db.resetError() db.runCommand(cmdObj) // run a database command. if cmdObj is a string, turns it into {cmdObj:1} db.setProfilingLevel(level) // 0=off 1=slow 2=all db.shutdownServer() db.version() // current version of the server

COLLECTION METHODS

db.foo.count() db.foo.dataSize() db.foo.distinct( key ) // eg. db.foo.distinct( 'x' ) db.foo.drop() // drop the collection db.foo.dropIndex(name) db.foo.dropIndexes() db.foo.ensureIndex(keypattern,options) // options should be an object with these possible fields: name, unique, dropDups db.foo.find( [query] , [fields]) // first parameter is an optional query filter. // second parameter is optional set of fields to return. // e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } ) db.foo.find(...).count() db.foo.find(...).limit(n) db.foo.find(...).skip(n) db.foo.find(...).sort(...) db.foo.findOne([query]) db.foo.getDB() // get DB object associated with collection db.foo.getIndexes() db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.foo.mapReduce( mapFunction , reduceFunction , <optional params> ) db.foo.remove(query) db.foo.renameCollection( newName ) // renames the collection db.foo.save(obj) db.foo.stats() db.foo.storageSize() // includes free space allocated to this collection db.foo.totalIndexSize() // size in bytes of all the indexes db.foo.totalSize() // storage allocated for all data and indexes db.foo.update(query, object[, upsert_bool, multi_record_bool]) db.foo.validate() // SLOW db.foo.getShardVersion() // only for use with sharding

UTILITIES

mongodump -d database_name -o /some/directory mongorestore -d database_name /some/directory

EXAMPLES

Inserting Data > j = { name: "mongo"}; {"name" : "mongo"} > t = { x : 3 }; { "x" : 3 } > db.things.save(j); > db.things.save(t); Accessing Data from a Query var cursor = db.things.find(); while (cursor.hasNext()) { print(tojson(cursor.next())); } Retrieving Data with Javascript functions db.things.find().forEach( function(x) { printjson(x);}); select * from things where name="mongo" db.things.find({name:"mongo"}).forEach(printjson); select * from things where x=4 db.things.find({x:4}).forEach(printjson); select j from things where x=4 db.things.find({x:4}, {j:true}).forEach(printjson); order by db.things.find().sort(x:1) // ascending db.things.find().sort(x:-1) // descending limit 1 var mongo = db.things.findOne({name:"mongo"}); print(tojson(mongo)); limit(x) db.things.find().limit(3); update users set api_token = 'snafu' where _id = "fubar"; db.users.update( { "_id" : "fubar" }, { $set : { "api_token" : "snafu" } }, false ); update or insert users set api_token = 'snafu' where _id = "fubar"; db.users.update( { "_id" : "fubar" }, { $set : { "api_token" : "snafu" } }, true ); Rename all fields in a collection db.users.update( {}, { $rename : {"old_field_name" : "new_field_name"}}, false, true);

MORE HELP

In addition to the general "help" command in mongo, you can call help on db and db.whatever to see a summary of methods available. MongoDB Manual: http://www.mongodb.org/display/DOCS/Manual

저작자 표시 비영리
신고
Posted by jeonguk

dbshell Reference

Database/MongoDB 2012.02.17 12:34 |


2012:02:17 12:31:34

2012:02:17 12:31:52


2012:02:17 12:32:12


2012:02:17 12:32:27


2012:02:17 12:32:45


2012:02:17 12:33:06




http://www.mongodb.org/display/DOCS/dbshell+Reference 

저작자 표시 비영리
신고
Posted by jeonguk

윈도우에서 spring + mongodb 설치해서 테스트 하다가

붓캠으로 윈도우 접속하고 하는게 귀찮아서

Mac OSX에 설치해서 테스트 하려고 하는데 뭐가 이리 해야하는게 많은지..

어휴..


공식 사이트에서 맥오에스에 mongodb 설치 테스트 하는 법을 따라 하다 보니

http://www.mongodb.org/display/DOCS/Quickstart+OS+X



brew가 없단다...

그래서 homebrew 설치 하러 고고

http://ascarter.net/2010/02/22/homebrew-for-os-x.html


하다 보니 또 git가 없단다

그래서 git 설치 하러 고고


http://code.google.com/p/git-osx-installer/downloads/list?can=3

패키지로 다운 받아서 설치


다시 brew update

이렇게 해서 brew까지 설치 하고

처음으로 돌아가서

mongodb설치 하자...ㅋㅋㅋ


알아서 64bit 바이너리 파일로 설치 해주네




맥포트로 설치하는 방법도 있다.

http://www.macports.org/install.php 맥포트 설치(스노레파드)



 
저작자 표시 비영리
신고

'Database > MongoDB' 카테고리의 다른 글

Cheat MongoDB  (0) 2012.02.17
dbshell Reference  (0) 2012.02.17
Mac OSX - mongodb 맥북프로에 설치  (0) 2012.02.05
windows CMD 창에서 mongoDB UTF8 collection 한글 데이터 확인  (0) 2012.02.04
Spring + mongoDB  (1) 2012.01.30
Java : Authentication access to MongoDB  (0) 2012.01.30
Posted by jeonguk

spring + mongodb 로 테스트 중인데

utf8로 데이터 입력 , 화면 출력할때는 한글이 정상적으로 입력 출력 되지만

cmd창에서 mongodb 쉘 접속 해서 컬렉션 데이터를 확인할 때에는 한글이 깨져서 확인이 안된다.

그래서 검색을 통해 확인 하는 방법을 알게되었다.


  한글 윈도우의 경우 기본적으로 명령 프롬프트의 코드는 949입니다. 



2012:02:04 20:51:45



chcp 명령어로 알아본 현재 활성 코드 페이지 번호 


이를 UTF8으로 바꾸면 된다.
바꾸기 전에 먼저 한글 폰트를 설정
title-bar(위 그림에서 C:\WINDOWS\system32\cmd.exe가 적혀져 있는 곳)에 마우스 커서를 두고 오른쪽 버튼을 클릭하면 메뉴가 뜬다.
속성을 클릭

2012:02:04 20:53:51


레스터 글꼴 대신에 굴림체 선택 
utf8 상태에서도 한글이 정상적으로 출력되도록한다.


2012:02:04 20:56:01


chcp 65001 명령어로 code page를 UTF8로 바꾼다. 화면이 변경 된다.


mongodb 접속

2012:02:04 20:59:34



이제 한글로 입력한 데이터가 cmd창에서 확인 된다.

* DB 실행은 chcp65001로 시작 안해도 됨
mongo 쉘 접속만 위 모드로 실행



저작자 표시 비영리
신고
Posted by jeonguk

Spring + mongoDB

Database/MongoDB 2012.01.30 17:14 |

  1. Spring Data MongoDB – 1.0.0.M2
  2. Spring Core – 3.0.5.RELEASE
  3. Java Mongo Driver – 2.5.2
  4. STS
  5. JDK – 1.6
  6. Maven – 3.0.3


1. 프로젝트 구조

2012:01:30 17:05:00




2. 의존 라이브러리

 spring-data-mongodb
Currently, the “spring-data-mongodb” jar is only available in “http://maven.springframework.org/milestone“, so, you have to declare this repository also.  




3. Maven  pom.xml 설정

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.spring.mongo</groupId>
  <artifactId>SpringMongoDB</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringMongoDB</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
  <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
 
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
 
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
 
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.5.2</version>
</dependency>
 
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.0.0.M2</version>
</dependency>
 
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
  </dependencies>
</project>




4.1 Spring 설정 annotation

 SpringMongoConfig.java 

package com.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;

import com.mongodb.Mongo;

/**
 * Spring MongoDB configuration file
 * @author jeonguk.lee
 *
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Override
public @Bean Mongo mongo() throws Exception {
return new Mongo("localhost");
}
    
 
       // Auth 설정으로 서버를 스타트 했으므로...
@Override
public @Bean MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mdb = new MongoTemplate(mongo(), "jeongukdb", "blog");
mdb.setUsername("jk");
mdb.setPassword("1111");
return mdb;
}
}




4.2 Spring 설정  XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

<!-- Default bean name is 'mongo' -->
<mongo:mongo host="localhost" port="27017" />
<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="jeongukdb" />
<constructor-arg name="defaultCollectionName" value="blog" />
<property name="username" value="jk" />
<property name="password" value="1111" />
</bean>
<!-- To translate any MongoException throws in @Repository annotated classes -->
<context:annotation-config />
</beans>



5. User Model

package com.spring.user;

public class User {
private String id;
private String firstname;
private String lastname;
private int age;
public User() {
}
public User(String id, String firstname, String lastname, int age) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return " id : " + this.id + " first name : " + this.firstname + " last name : " + this.lastname + " age : " + this.age;
}
}



6. CRUD TEST

MongoTemplate implemented MongoOperations interface. 


App.java 

package com.spring.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;

import com.spring.config.SpringMongoConfig;
import com.spring.user.User;


public class App {

public static void main( String[] args ) {
//For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
//For XML
//ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
MongoOperations mongoOperation =(MongoOperations)ctx.getBean("mongoTemplate");
User user = new User("1001", "Lee", "Jeonguk", 35);
//save
mongoOperation.save("userprofile",user);
//find
User savedUser = mongoOperation.findOne("userprofile", new Query(Criteria.where("id").is("1001")), User.class);
System.out.println("savedUser :" + savedUser);
//update
mongoOperation.updateFirst("userprofile", new Query(Criteria.where("firstname").is("Lee")), Update.update("lastname", "new lastname"));
//find
User updatedUser = mongoOperation.findOne("userprofile", new Query(Criteria.where("id").is("1001")),User.class);
System.out.println("updateUser :" + updatedUser);
//delete
mongoOperation.remove("userprofile", new Query(Criteria.where("id").is("1001")),User.class);
//List
List<User> listUser = mongoOperation.getCollection("userprofile", User.class);
System.out.println("Number of user = " + listUser.size());
    }
}


 
7. 결과

savedUser : id : 1001 first name : Lee last name : Jeonguk age : 35
updateUser : id : 1001 first name : Lee last name : new lastname age : 35
Number of user = 0

 
저작자 표시 비영리
신고
Posted by jeonguk

Authentication 설정


1. mongoDB 실행

2012:01:30 12:46:13



2. cmd창을 하나 더  열어서 쉘 접속

2012:01:30 12:48:43



3.  Database에 사용자 생성

2012:01:30 12:39:08



4. 테스트

2012:01:30 12:51:46


 5. mongoDB Secure Mode로 재시작

2012:01:30 12:33:50

 

6. JAVA 샘플 코드

package com.jeonguk.core;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class AuthTest {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("jeongukdb");
boolean auth = db.authenticate("jk", "1111".toCharArray());
System.out.println("auth : "+auth);
DBCollection collection = db.getCollection("jeongukCollection");
            // search query
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("id", 1001);
   
           // query it
           DBCursor cursor = collection.find(searchQuery);
   
           // loop over the cursor and display the retrieved result
           while (cursor.hasNext()) {
            System.out.println(cursor.next());
           }
   
System.out.println("Done");
} catch(UnknownHostException e) {
e.printStackTrace();
} catch(MongoException e) {
e.printStackTrace();
}

}

}
 

신고
Posted by jeonguk