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

最前言

這是我上學期寫的文章,算是教程,最初發(fā)在我自己的網(wǎng)站上,其實更應該算作是學習筆記吧,因為有些代碼我也得回來看一眼才能想起來。從最基礎的 MongoDB 的 Shell 端開始學習,然后學習 Web 開發(fā),然后做了個非常簡單的 Demo, 基于 MongoDB, Java, Heroku, SparkAngularJSWeb App。因為都是用英文學的,學校里與人交流也是用英文,所以就用英文寫了,但我最近寫的 Swift 學習的幾片文章全是中文的,我知道你們都不愛看英文 :) 但這兩篇實在是懶得再翻譯成中文了。。。所以對 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.


歡迎轉載,轉載請注明出處。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,097評論 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,660評論 5 6
  • 我希望有一座山,山上有森林、湖泊和飛鳥,抬眼望去便是漫天星光。山中只有一所房子,房子中住著你我。夏天時我們會在林中...
    南山劉郎閱讀 217評論 0 0
  • 一直想要看路遙的《人生》,高三把《平凡的世界》看完了,得知還有《人生》這一本書的時候,已經(jīng)沒有時間看了,因為要...
    虛實先森閱讀 488評論 0 21
  • 4.1 什么是社群 社群的大前提是人的社會性,社區(qū)是人的社會性在互聯(lián)網(wǎng)時代的折射,到了移動互聯(lián)網(wǎng)時代,這種折射的表...
    一泉閱讀 369評論 0 0

友情鏈接更多精彩內容