조회 

 

 

 

등록 

 

 

 

삭제 

 

 

복합인덱스는 항목만 추가해주면된다. 

 

Ex )db.collection.createIndex({ name: 1, site: -1 })  


'오락기 > mongoDB' 카테고리의 다른 글

mongoose.js node 연동  (0) 2018.08.17
query rdb와 동일하게 할려면  (0) 2018.08.17
sort lime skip  (0) 2018.08.17
aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17

import mongoose from 'mongoose' 

let db = mongoose.connection 

db.on('error'console.error); 

db.once('open', () => { 

// CONNECTED TO MONGODB SERVER 

console.log("Connected to mongod server"); 

}); 

mongoose.connect('mongodb://jsplays.iptime.org:27017/resource') 

 

커넥션  이렇게 

mongoose.connect('mongodb://username:password@host:port/database?options...'); 

 

 

let schema = mongoose.Schema 

let testSchema = new schema({ 

title : String, 

auth : String, 

date : { type : Date , default : Date.now} 

}) 

 

 

스키마 지정 

사용되는 스키마는 8종류 

 

  1. String 

  2. Number 

  3. Date 

  4. Buffer 

  5. Boolean 

  6. Mixed 

  7. Objectid 

  8. Array 

 

import mongoose from 'mongoose' 

const schema = mongoose.Schema 

const testSchema = new mongoose.schema ({ 

test : {type : Number , require : true , unique : true}, 

title : String, 

auth : String, 

date : { type : Date , default : Date.now} 

}, 

{ 

timestamps: true 

} 

) 

//콜렉션 이름을 지정하고싶으면 스키마 생성시 옵션으로 넣는다 

// const todoSchema = new mongoose.Schema({..}, { collection: 'my-collection-name' }); 

//모델은 생성자이므로 인스턴스를 생성할수있음으로 속성이나 값을 추가하여 생성할수있다 

const Test = mongoose.model('Test' , testSchema) 

const test = new Test({ 

test : 1, 

title: 'test', 

auth : 'js' 

}) 

또는 

const test = new Test() 

test.test = 1 

test.title = 'test' 

test.auth = 'js' 

const output = mongoose.model('Test' , testSchema) 

export default output 

 

 

관계는 이렇게 될수있다. 

 

 

 


'오락기 > mongoDB' 카테고리의 다른 글

index 관리  (0) 2018.09.28
query rdb와 동일하게 할려면  (0) 2018.08.17
sort lime skip  (0) 2018.08.17
aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17

여러가지 데이터를 찾을때 QUERY 문법이 생소하여 따로 문서로 정리 

 

 

 

 select * from dogdrip  같다 

 

WHERE  추가 

 

Seelct * from dogdrip where date = '2017-12-31' 

 

 

WHERE IN  

 

 

 

 

Select * from dogdrip where num in ("138584" ,"138583" 

 

 

WHERE AND 

 

 

 

Select * from dogdrip where date = '2017-12-31' and num < 138580 

 

WHERE OR 

 

 

Select * from dogdrip where date = ' 2017-12-31' or num < 3 

 


'오락기 > mongoDB' 카테고리의 다른 글

index 관리  (0) 2018.09.28
mongoose.js node 연동  (0) 2018.08.17
sort lime skip  (0) 2018.08.17
aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17


'오락기 > mongoDB' 카테고리의 다른 글

mongoose.js node 연동  (0) 2018.08.17
query rdb와 동일하게 할려면  (0) 2018.08.17
aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
upset + java api  (0) 2018.08.17

검색시 sort 여러가지 옵션으로 검색하게 되면 

결과값이 많이 나오거나 많은 양을 데이터를 검색시 메모리 오류가 난다. 

 

 

 

 메모리를 늘리는 방법도 가능하다리미트를 주는방식도 가능하다 

 

db.getCollection('dogdrip').find({}).sort( {"date" : -1}).limit(1 

 

 

이러한 일련의 과정을 한번에 해결해주는 방법이 있다. 

 

몽고디비에 데이터 집계를 위한 프레임워크가 있다.  Aggregate라는것이다. 

 

 

 

이렇나 파이프라인 구조로 데이터를 줄여가며 보여주게 된다. 

 

파이프 라인구성 문법들은 다음과같다. 

 

 

 

 

정말 많다 레벨을 구성하여 데이터를 줄여나갈수있다. 

 

이에 따른 옵션도 굉장히 많다. 

 

 

 

 

공식문서로 확인할수있음 

 

이것을 토대로 위에 소트한 내용을 다시 한번 하게되면 

 

 

 

 

이런식으로 구성할수있다. 

 

좀더 쉽게  집계할 수잇는 방법이 있는거같다 

 

Java jdbc  해보자 어렵지않다 그대로 써주면된다. 

 

 

AggregationOutput com.mongodb.DBCollection.aggregate(List<? extends DBObject> pipeline) 

Deprecated. Use aggregate(List, AggregationOptions) instead 

Method implements aggregation framework. 

Parameters: 

pipeline operations to be performed in the aggregation pipeline 

Returns: 

the aggregation's result set 

@mongodb.driver.manual 

core/aggregation-pipeline/ Aggregation 

@mongodb.server.release 

2.2 

 

 

TRICK TO CONVERT MONGO SHELL QUERY INTO EQUIVALENT JAVA OBJECTS 

Earlier we completed with Mongodb aggregation , examples and shell queries.Still this time I have something thing to share.We learned aggregation queries and its bit easier while writing in to the mongo shell because initially we learned it via shell.But while implementing some application we need to convert it into the appropriate programming language. 

This article is written aiming to the java developers as its quite complex in java while creating large aggregation query comparing to node.js or python which is much similar to shell query in terms of syntax. 

But after reading this article it would be easier to write aggregation queries in java also.Considering one example fromdocs.mongodb.org we will see how to do it. 

Below is a simple dataset for the example. 

{  "_id" : ObjectId("503d5024ff9038cdbfcc9da4"), 
   "employee" : 1, 
   "department" : "Sales", 
   "amount" : 77, 
   "type" : "airfare" 
} 

Above query illustrate the $match operator example using aggregation function. This query will display all the documents that have type = local. I have simplified this query usingkey-value (here we separate key-value by : ) partition as you can see in above image.Now you know that how to decompose aggregation query into key-value pair and value into the further key-value pair and so on. 

Now coming to the java part, java driver uses theBasicDBObject class to construct the aggregation query.One of the BasicDBObject’s constructor contains two parameters as below. 

new BasicDBObject(String key , Object value); 

Now mapping “String key” with the key in shell query and “Object value” with the value in shell query. 

After this now i’ll write java code so you can clearly understand how its done. 

DBObject match = new BasicDBObject("$match", new BasicDBObject("type""local")); 

In few cases you can have multiple details under value part separated by comma ( , ) as below,So we can use.append(String key , Object value) method. 

SHELL :  
db.aggregationExample.aggregate( 
       {$project : { department : 1 , amount : 1 }} 
); 
 

JAVA :  
DBObject project = new BasicDBObject("$project" ,  
       new BasicDBObject("department" , 1).append("amount" , 1)); 

Final Example 

public class JavaAggregation { 
public static void main(String args[]) throws UnknownHostException{ 
MongoClient mongo = new MongoClient(); 
DB db = mongo.getDB("pingax"); 
 

DBCollection coll = db.getCollection("aggregationExample"); 
 

/* 
MONGO SHELL : db.aggregationExample.aggregate( 
{$match : {type : "local"}} , 
{$project : { department : 1 , amount : 1 }} , 
{$group : {_id : "$department" , average : {$avg : "$amount"} } } , 
{$sort : {"amount" : 1}} 
); 
*/ 
DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "local"));  
 

DBObject project = new BasicDBObject("$project", new BasicDBObject("department", 1) 
.append("amount", 1)); 
 

DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$department") 
.append("avrage", new BasicDBObject("$avg", "$amount"))); 
 

DBObject sort = new BasicDBObject("$sort", new BasicDBObject("amount", 1)); 
 

AggregationOutput output = coll.aggregate(match,project,group,sort); 
 

for (DBObject result : output.results()) { 
System.out.println(result); 
} 
} 
} 
 

OUTPUT :  
{ "_id" : "Development" , "avrage" : 111.0} 

 

 

 

 

 

 

 

 

 

 

 

 

 


'오락기 > mongoDB' 카테고리의 다른 글

query rdb와 동일하게 할려면  (0) 2018.08.17
sort lime skip  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
upset + java api  (0) 2018.08.17
JDBC 연동  (0) 2018.08.17

db.collection.distinct( "field") 

 

 

Java에서도 api제공 

 

public List findDistinct(String key){ 

List list = userTable.distinct(key); 

return list; 

 

} 

 


'오락기 > mongoDB' 카테고리의 다른 글

sort lime skip  (0) 2018.08.17
aggregation pipeline stages  (0) 2018.08.17
upset + java api  (0) 2018.08.17
JDBC 연동  (0) 2018.08.17
기본 명령어들  (0) 2018.08.17

몽고 db에선 머지 작업대신에 upsert라는 작업이 있다 

업데이트할 자료가 없다고하면 insert 시킨다. 

 

Update 대한 옵션으로  ( 쿼리 , 변경값 , 옵션인데 옵션부분에 들어가면된다 

 

db.test.update(  

                {test1 : "2" }, 

                { $set :  

                       {test3 : 14 } 

                 }  

                 ,  { upsert: true } 

              ) 

 

일경우 test2 있으면 test3 14 업데이트하고 

Test2 없으면 도큐먼트를 하나 생성하여 test2 : 2 test3 : 14 넣게된다. 

 

 

 

여기서 test 2 test3 15 변경 

 

 

 

 되며 

 

만약 test1 값이 3이라고 한다면 

 

 

 

 

 

이런식으로 도큐먼트가 하나 생성된다. 

데이터 입력시 중복제거로  쓸수잇을꺼같다. 

 

 

자바에서는 어떻게 표현할 수있을지 본다. 

 

 

업데이트에 있기도하며 

 

으로도 존재한다 

후자는 아직 어떻게 사용하는지 모르겠다. 

 


'오락기 > mongoDB' 카테고리의 다른 글

aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
JDBC 연동  (0) 2018.08.17
기본 명령어들  (0) 2018.08.17
RDBMS 용어 차이  (0) 2018.08.17

package common.DBConnect; 

 

import org.junit.Test; 

 

import com.mongodb.BasicDBObject; 

import com.mongodb.DB; 

import com.mongodb.DBCollection; 

import com.mongodb.DBCursor; 

import com.mongodb.MongoClient; 

import com.mongodb.ServerAddress; 

 

public class DBconnect { 

 

 

MongoClient mongoClient = null; 

DB db = null; 

 

private void DBconnection(){ 

 

String ip = "localhost"; 

int port = 27017; 

String dbName = "test"; 

 

this.mongoClient = new MongoClient(new ServerAddress(ip, port)); 

this.db = this.mongoClient.getDB(dbName); 

 

} 

 

public void insert(){ 

 

DBconnection(); 

DBCollection userTable = db.getCollection("books"); 

        BasicDBObject doc = new BasicDBObject("name", "MongoDB"). 

        append("type", "database"). 

        append("count", 1). 

        append("info", new BasicDBObject("name", "js")); 

         

        userTable.insert(doc); 

 

} 

 

@Test 

public void find(){ 

 

DBconnection(); 

DBCollection userTable = db.getCollection("books"); 

BasicDBObject query = new BasicDBObject("name" ,"Book3"); 

 

DBCursor cursor = userTable.find(query); 

 

while(cursor.hasNext()){ 

System.out.println(cursor.next()); 

} 

} 

} 


'오락기 > mongoDB' 카테고리의 다른 글

aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
upset + java api  (0) 2018.08.17
기본 명령어들  (0) 2018.08.17
RDBMS 용어 차이  (0) 2018.08.17

디비부터 만들어보자꾸나 

 

현재 사용 확인 

 

 

 

사용량 확인 

 

 

방금 만든거 없다도큐먼트가 없어서 그런거랍니다. 

 

 

 

 

한번 해본다. 

 

 

나온당 

 

 

 

없애보자꾸나 

 

우선 선택하고 

 

 

 

업어짐 

 

컬렉션 생성보자꾸나 

 use test 

 

 

물론 도큐먼트만 만들어도 컬렉션 생성됨 편하당 

 

이건 articles 컬렉션 옵션을 정의 

 

 

참고- 

제 예제에서 books 컬렉션을 capped: true 옵션으로 생성하게 했었네요. 

이 부분 수정 했습니다. 기존에 만들어진 컬렉션을 drop 하시고, 

books 컬렉션을 옵션 없이 설정 하면 문제가 해결 될거에요. 

참고로 capped collection 은 빈공간을 관리하지 않기때문에 Insert 속도가 빠른대신에 Delete 가 안된답니다 

 

 

 

 

이건 도큐먼트 추가하면 자동으로 컬렉션 생성 

 

 

컬렉션 보기 

 

 

컬렉션 드랍 

 

 

도큐먼트 추가 

 

 

기본적인형태 

 

 

 

여러줄도 가능 

 

 

 

 

찾기 

 

제거는 

파라미터는 

 

parameter 

type 

설명 

*criteria 

document 

삭제 할 데이터의 기준 값 (criteria) 입니다. 이 값이 { } 이면 컬렉션의 모든 데이터를 제거합니다. 

justOne 

boolean 

선택적(Optional) 매개변수이며 이 값이 true 면 1개 의 다큐먼트만 제거합니다. 이 매개변수가 생략되면 기본값은 false 로 서, criteria에 해당되는 모든 다큐먼트를 제거합니다. 

 

 

라고합니다. 

 

 

8건잇는걸 

 

 

 

삭제합니다 

 

 

 


'오락기 > mongoDB' 카테고리의 다른 글

aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
upset + java api  (0) 2018.08.17
JDBC 연동  (0) 2018.08.17
RDBMS 용어 차이  (0) 2018.08.17

RDB 

MongoDB 

데이터베이스 

데이터베이스 

테이블 

컬렉션 

듀플/로우 

도큐먼트 

컬럼 

필드 

테이블 조인 

Embedded documents 

기본키 

기본키( _id제공 ) 


'오락기 > mongoDB' 카테고리의 다른 글

aggregation pipeline stages  (0) 2018.08.17
distinct + java api  (0) 2018.08.17
upset + java api  (0) 2018.08.17
JDBC 연동  (0) 2018.08.17
기본 명령어들  (0) 2018.08.17

+ Recent posts