基于 MongoDB 的 Web APP(建于 Heroku)-PART 1

最前言

這是我上學(xué)期寫的文章涎劈,算是教程最冰,最初發(fā)在我自己的網(wǎng)站上窘哈,其實(shí)更應(yīng)該算作是學(xué)習(xí)筆記吧,因?yàn)橛行┐a我也得回來看一眼才能想起來胧洒。從最基礎(chǔ)的 MongoDB 的 Shell 端開始學(xué)習(xí)畏吓,然后學(xué)習(xí) Web 開發(fā),然后做了個(gè)非常簡(jiǎn)單的 Demo, 基于 MongoDB, Java, Heroku, SparkAngularJSWeb App卫漫。因?yàn)槎际怯糜⑽膶W(xué)的菲饼,學(xué)校里與人交流也是用英文,所以就用英文寫了列赎,但我最近寫的 Swift 學(xué)習(xí)的幾片文章全是中文的宏悦,我知道你們都不愛看英文 :) 但這兩篇實(shí)在是懶得再翻譯成中文了。包吝。饼煞。所以對(duì) MongoDB 有興趣的童鞋就將就看看吧。

Foreword

Sometimes you spend tons and tons of time just looking for one method or function or even one simple syntax, but with no result.

Suddenly, you get the answer, and it is on a very common webpage.

"WTF, this is a fking waste of time! Why can't I find it earlier, instead of suffering so much pain?!"

I don't know. Maybe this is exactly the difficulty that stops most people becoming a good engineer. You know, I am still struggling on this way. However, when I write the post, I am happy.

Now, let's get started with our project.)

Add a MongoDB to your Heroku application

First, we need to add a MongoDB database to your Heroku application. There are two choices, Compose MongoDB and mLab MongoDB. Compose MongoDB has no free plan, whereas mLab has a free plan - sandbox. Here I use Compose MongoDB.

To add a Compose database to your Heroku application (using your console):

$ heroku addons:create mongohq:ssd_1g_elastic 

To add a mLab MongoDB (free plan):

$ heroku addons:create mongolab

Use the heroku config command to view your app’s config variables. The URL contains all the MongoDB connection information you will need to connect to your database.

$ heroku config | grep MONGOHQ_URL

Now, you can use the MONGOHQ_URL variable in code and configurations for your driver, depending on the language you app is created in, connecting and authenticating to your MongoDB database hosted with Compose.

Use with Java

==NOTE==: The syntaxes between 2.x and 3.x are very different. If you don't want to waste a lot of time like me, please make it clear what version of mongo-java-driver you are using.

Add the Mongo Java driver to your pom.xml

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.2.2</version>
</dependency>

And this is apache.maven.plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
</plugin>

Use MongoDB in your application

    MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
    //get connected
    DB db = mongoURI.connectDB();
    // authenticate
    // (version 2.7.2) db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());
    MongoCredential credential = MongoCredential.createCredential(mongoURI.getUsername(), mongoURI.getDatabase(), mongoURI.getPassword());
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));

Setting Write Concern

mongoClient.setWriteConcern(WriteConcern.JOURNALED);

As of version 2.10.0, the default write concern is WriteConcern.ACKNOWLEDGED, but it can be easily changed.

Use MongoDB with Spring.

And here is a sample code. (==Note==: this sample is under 2.7.2 version, now the newest is 3.2.2 which I am using)

==Note:== Java MongoDB driver provides its own connection pooling by default, and it's thread safe. See the details in the docs.

CRUD

Get collection names. (like show databases):

Set<String> colls = db.getCollectionNames();
System.out.println("Collections found in DB: " + colls.toString());

Get a collection (for CRUD):

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

Let's assume a json dataset like this:

{
“name” : “MongoDB”,
“type” : “database”,
“count” : 1,
“info” : {x : 203, y : 102}
}

To insert this dataset into MongoDB, there are two ways shown bellow. I prefer using .append.

BasicDBObject doc = new BasicDBObject("name", "MongoDB")
    .append("type", "database")
    .append("count", 1)
    .append("info", new BasicDBObject("x", 204).append("y", 103));
    coll.insert(doc);

Another way to insert data.

     BasicDBObject doc = new BasicDBObject();
     
     doc.put(“name”, “MongoDB”);
     doc.put(“type”, “database”);
     doc.put(“count”, 1);
     
     BasicDBObject info = new BasicDBObject();
     
     info.put(“x”, 203);
     info.put(“y”, 102);
     
     doc.put(“info”, info);
     
     coll.insert(doc);

Get the first document:

DBObject myDoc = coll.findOne();
System.out.println(myDoc);

Get the total amount of documents:

System.out.println(coll.getCount());

Using a Cursor to Get All the Documents:

DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

Getting A Single Document with A Query:

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

DBCursor cursor = coll.find(query);

try {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
} finally {
    cursor.close();
}

You may know this kind of statement, which is in shell:

$ db.things.find({j: {$ne: 3}, k: {$gt: 10} });

You can implement in the java driver, using embedded DBObjects:

query = new BasicDBObject("j", new BasicDBObject("$ne", 3))
    .append("k", new BasicDBObject("$gt", 10));

cursor = coll.find(query);

try {
while(cursor.hasNext()) {
    System.out.println(cursor.next());
}
} finally {
cursor.close();
}

Create index list:

//create index诗越,1 for ascending砖瞧,-1 for descending
coll.createIndex("name"); //Forces creation of an ascending index on a field with the default options.
//get the index list
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}

See more methods of DBCollection please refer to this docs. You can also find other index types there.


歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明出處嚷狞。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末块促,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子床未,更是在濱河造成了極大的恐慌褂乍,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件即硼,死亡現(xiàn)場(chǎng)離奇詭異逃片,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門褥实,熙熙樓的掌柜王于貴愁眉苦臉地迎上來呀狼,“玉大人,你說我怎么就攤上這事损离「缤В” “怎么了?”我有些...
    開封第一講書人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵僻澎,是天一觀的道長(zhǎng)貌踏。 經(jīng)常有香客問我,道長(zhǎng)窟勃,這世上最難降的妖魔是什么祖乳? 我笑而不...
    開封第一講書人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮秉氧,結(jié)果婚禮上眷昆,老公的妹妹穿的比我還像新娘。我一直安慰自己汁咏,他們只是感情好亚斋,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著攘滩,像睡著了一般帅刊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上漂问,一...
    開封第一講書人閱讀 51,245評(píng)論 1 299
  • 那天厚掷,我揣著相機(jī)與錄音,去河邊找鬼级解。 笑死冒黑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的勤哗。 我是一名探鬼主播抡爹,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼芒划!你這毒婦竟也來了冬竟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤民逼,失蹤者是張志新(化名)和其女友劉穎泵殴,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體拼苍,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡笑诅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吆你。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡弦叶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出妇多,到底是詐尸還是另有隱情伤哺,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布者祖,位于F島的核電站立莉,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏七问。R本人自食惡果不足惜蜓耻,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望烂瘫。 院中可真熱鬧媒熊,春花似錦奇适、人聲如沸坟比。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽葛账。三九已至,卻和暖如春皮仁,著一層夾襖步出監(jiān)牢的瞬間籍琳,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工贷祈, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留趋急,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓势誊,卻偏偏與公主長(zhǎng)得像呜达,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子粟耻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,486評(píng)論 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,471評(píng)論 5 6
  • 我希望有一座山查近,山上有森林、湖泊和飛鳥挤忙,抬眼望去便是漫天星光霜威。山中只有一所房子,房子中住著你我册烈。夏天時(shí)我們會(huì)在林中...
    南山劉郎閱讀 188評(píng)論 0 0
  • 一直想要看路遙的《人生》戈泼,高三把《平凡的世界》看完了,得知還有《人生》這一本書的時(shí)候,已經(jīng)沒有時(shí)間看了矮冬,因?yàn)橐?..
    虛實(shí)先森閱讀 436評(píng)論 0 21
  • 4.1 什么是社群 社群的大前提是人的社會(huì)性谈宛,社區(qū)是人的社會(huì)性在互聯(lián)網(wǎng)時(shí)代的折射,到了移動(dòng)互聯(lián)網(wǎng)時(shí)代胎署,這種折射的表...
    一泉閱讀 340評(píng)論 0 0