Javaを使いデータをMongoDBに入れてみた
こんにちは、鬱太郎です。今日はプログラムからMongoDBにデータを入れる実験をしたので、それについてまとめたいと思います。
- jarドライバーをダウンロードする
- プログラムからMongoDBを検索する
- プログラムからMongoDBにデータを追加する
- Twitterの自分のユーザー情報を追加してみる
- 希望の党のフォロワーIDを取得する
- まとめ
jarドライバーをダウンロードする
下記リンクからドライバーをダウンロードします。
Index of /repositories/releases/org/mongodb/mongo-java-driver/3.5.0
mongo-java-driver-x.x.x.jar
というものをダウンロードし、環境変数等に登録しておきましょう。私はEclipseの外部JARに追加しました。


プログラムからMongoDBを検索する
MongoClient client = new MongoClient("localhost", 27017);
で指定したアドレス、ポート番号で接続を確立させる。MongoDatabase db = client.getDatabase("testdb");
で指定したデータベースを使う。クライアントでのuse testdb
と同じMongoCollection<Document> coll = db.getCollection("test");
でコレクションを指定する。この変数に検索・追加等を行う場合はこのコレクションに行う。
特に特筆する点はありませんでした。Document
クラスは他のパッケージでも使われるため、org.bson.Document
という風に明示しておく必要があるくらいでしょうか?
実行結果は下のようになります。これまでにいろいろとデータを追加したりしていたので、汚れていますね…
8 Document{{_id=59ddaf21ee43c8a85e9dfea5, name=testinsert, message=hello mongodb, testv=org.bson.BsonUndefined@0, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddb11dee43c8a85e9dfea6, name=ニート鬱太郎, message=テストメッセージ, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddb5e19a2f587d7ea7001a, name=ニート鬱太郎, message=ストメッセージ, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddb5ff9a2f587d7ea7001b, test=false, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddb8879a2f587d7ea7001c, testname=tet, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddb9c09a2f587d7ea7001d, id=9.0232311199491686E17, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}} Document{{_id=59ddbd099a2f587d7ea7001e, created_at=Tue Aug 29 09:12:49 GMT+09:00 2017}} Document{{_id=59ddbf9b9a2f587d7ea7001f, createdAt=Tue Oct 10 19:00:05 GMT+09:00 2017, created_at=Thu Jan 01 09:00:00 GMT+09:00 1970}}
プログラムからMongoDBにデータを追加する
db.createCollection("test1");
でデータベースにコレクションを追加します。coll.insertOne(Document.parse(json));
でコレクションにデータを追加します。
データを追加する際はorg.bson.Document
クラスとして追加する必要があります。文字列のJSONがある場合は下の例のようにDocument.parse(json)
でDocument
型に変換できます。
結果
> db.test1.find() { "_id" : ObjectId("59e17ea9ae898d27ec86e0e9"), "name" : "test", "value" : 111,"created_at" : "Sat Oct 14 12:04:09 GMT+09:00 2017" }
Twitterの自分のユーザー情報を追加してみる
目的であるフォロワーの情報の取得の前に、自分のユーザー情報を追加してみます。
JSONObject json = new JSONObject(user);
でユーザー情報のJSONを作ります。coll.insertOne(Document.parse(json.toString()));
でJSONの文字列からDocument
クラスに変換しMongoDBに追加します。
結果です
> db.test.find({},{_id:0,status:0}) { "miniProfileImageURL" : "http://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_mini.jpg", "screenName" : "neet_utsu_taro", "contributorsEnabled" : false, "profileUseBackgroundImage" : false, "profileBackgroundTiled" : false, "createdAt" : "Tue Aug 29 09:12:49 GMT+09:00 2017", "profileBackgroundImageURL" : "http://abs.twimg.com/images/themes/theme1/bg.png", "biggerProfileImageURL" : "http://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_bigger.jpg", "protected" : false, "miniProfileImageURLHttps" : "https://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_mini.jpg", "profileImageURLHttps" : "https://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_normal.jpg", "id" : NumberLong("902323111994916864"), "profileImageURL" : "http://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_normal.jpg", "profileSidebarBorderColor" : "000000", "utcOffset" : -25200, "URLEntity" : { "displayURL" : "neetaro.com", "start" : 0, "end" : 23, "text" : "https://t.co/8tj7yW4gCF", "expandedURL" : "http://www.neetaro.com", "URL" : "https://t.co/8tj7yW4gCF" }, "timeZone" : "Pacific Time(US & Canada)", "defaultProfile" : false, "profileLinkColor" : "91D2FA", "originalProfileImageURLHttps" : "https://pbs.twimg.com/profile_images/902325250867716096/IXHm182E.jpg", "profileSidebarFillColor" : "000000", "rateLimitStatus" : { "limit" : 75, "secondsUntilReset" : 900, "remaining" : 74, "resetTimeInSeconds" :1507952068 }, "profileBannerMobileURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/mobile", "name" : "ニート鬱太郎", "followersCount": 69, "followRequestSent" : false, "showAllInlineMedia" : false, "geoEnabled" :false, "profileBannerMobileRetinaURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/mobile_retina", "translator" : false, "description" : "ニートです。どうでもいいこと言います。趣味アニメ等 だけども最近全く見てない。。。フォローされたら、bot等でない限りフォロー返します。 犬は柴犬、猫は黒猫が好き。 柴犬っていいよね…The犬って感じで _(:3」∠)_ ブログやってます。下のリンクからどうぞ。", "profileTextColor" : "000000", "descriptionURLEntities" : [ ], "URL" : "https://t.co/8tj7yW4gCF", "biggerProfileImageURLHttps" : "https://pbs.twimg.com/profile_images/902325250867716096/IXHm182E_bigger.jpg", "profileBannerIPadURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/ipad", "lang" : "ja", "defaultProfileImage" : false, "statusesCount" : 192, "accessLevel" : 2, "profileBackgroundImageUrlHttps" : "https://abs.twimg.com/images/themes/theme1/bg.png", "profileBackgroundColor" : "000000", "verified" : false, "favouritesCount" : 218, "friendsCount" : 105, "listedCount" : 0, "profileBannerURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/web", "location" : "自宅", "profileBannerRetinaURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/web_retina", "originalProfileImageURL" : "http://pbs.twimg.com/profile_images/902325250867716096/IXHm182E.jpg", "profileBannerIPadRetinaURL" : "https://pbs.twimg.com/profile_banners/902323111994916864/1505292216/ipad_retina" } >
希望の党のフォロワーIDを取得する
試しに、希望の党のフォロワーIDを取得してみます。TwitterAPIのfollowers/ids
は15分に15回しかアクセスできません。1回に5000人のIDを取得します。
プログラムを作る前には10600人のフォロワーがいます。3回のアクセスで取得できますね。
プログラムの標準出力
5000件取得 5000件取得 607件取得
MongoDBの結果
> db.ki db.kibounotou_ids db.killOP( db.killOp( > db.kibounotou_ids.find({},{_id:0}); { "user_id" : NumberLong(152582955) } { "user_id" : NumberLong("805586963134722048") } { "user_id" : NumberLong(207533598) } { "user_id" : NumberLong("2366735000") } { "user_id" : NumberLong("2578806756") } { "user_id" : NumberLong(101443148) } { "user_id" : NumberLong("2381150839") } { "user_id" : NumberLong("858242448211836928") } { "user_id" : NumberLong("853963341563285505") } { "user_id" : NumberLong(1895710039) } { "user_id" : NumberLong("919038152525758464") } { "user_id" : NumberLong("701664499904819200") } { "user_id" : NumberLong("4026560532") } { "user_id" : NumberLong("2401011818") } { "user_id" : NumberLong("3969213373") } { "user_id" : NumberLong(124797590) } { "user_id" : NumberLong(189854952) } { "user_id" : NumberLong(108766513) } { "user_id" : NumberLong("2328720366") } { "user_id" : NumberLong(1458820586) } Type "it" for more > db.kibounotou_ids.find({},{_id:0}).count(); 10607 >
10607人のユーザーIDを取得できました。私がプログラムを作っている間に7人のフォロワーが増えたようですね。
このユーザーIDはhttps://twitter.com/intent/user?user_id=
の=の先につけることでそのユーザーの情報をブラウザでも見ることができます。ちなみに私の情報はhttps://twitter.com/intent/user?user_id=902323111994916864
です。
まとめ
プログラムからMongoDBにデータを追加することができました!次はすべての政党のフォロワーのIDをデータベースに追加したいと思います。
その次に、追加したユーザーIDを元にユーザー情報を取得したいと思います。
またね('ω')ノ