java操作mongodb樣本分享_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

package mymaven; 

import java.net.UnknownHostException; 
import java.util.Set; 

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

public class Test { 
    public static void main(String[] args) throws UnknownHostException, MongoException { 
        Mongo mongo = new Mongo("172.27.9.104", 27017);     // 串連資料庫 
        DB db = mongo.getDB("mytestdb");                    // 資料庫 
        Set<String> cols = db.getCollectionNames();           // 擷取資料庫中所有的集合(類似於擷取關聯式資料庫中的表) 

        // 列印出資料庫中的集合,這裡應當為null 
        for (String s : cols) { 
            System.out.println(s); 
        } 

        DBCollection collection = db.getCollection("mytestcoll");       // 建立一個集合 
        collection.drop();                                              // 刪除集合,插入資料時自動重建 
        BasicDBObject obj = new BasicDBObject();                        // 初始化一個基本DB對象,插入資料庫的就是DB對象 

        obj.put("from", "blog.ithomer.net");        // 放入幾個索引值對 
        obj.put("to", "forum.ithomer.net"); 
        obj.put("subject", "ithomer.net"); 
        collection.insert(obj);                     // 插入對象 

        DBObject dbobj = collection.findOne();      // 查看一條記錄,findOne()=find().limit(1); 
        System.out.println(dbobj);                  // 列印出剛才插入的資料 

        // 插入10條{ranking:i}的資料 
        for (int i = 0; i < 10; i++) { 
            collection.insert(new BasicDBObject().append("ranking", i)); 
        } 
        System.out.println("count: " + collection.getCount());      // 列印集合中的資料總數 

         
        DBCursor cursor = collection.find();        // 然後我們使用這個遊標來遍曆集合 
        while (cursor.hasNext()) { 
            System.out.println(cursor.next()); 
        } 
        // 簡單的條件查詢,查詢ranking為1的記錄 
        BasicDBObject query = new BasicDBObject(); 
        query.put("ranking", 1); 
        cursor = collection.find(query); 
        System.out.println("collection find({\"ranking\":1}):"); 
        while (cursor.hasNext()) { 
            System.out.println(cursor.next()); 
        } 

        // 複雜的條件查詢,查詢ranking大於等於5小於9的記錄 
        query = new BasicDBObject(); 
        query.put("ranking", new BasicDBObject("$gte", 5).append("$lt", 9)); 
        cursor = collection.find(query); 
        System.out.println("collection find({\"ranking\":[5-9)}):"); 
        while (cursor.hasNext()) { 
            System.out.println(cursor.next()); 
        } 

//      mongo.dropDatabase("mytestdb");         // 最後刪除我們的測試資料庫 
    } 

運行結果:

複製代碼 代碼如下:

mytestcoll
system.indexes
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10107"} , "from" : "blog.ithomer.net" , "to" : "forum.ithomer.net" , "subject" : "ithomer.net"}
count: 11
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10107"} , "from" : "blog.ithomer.net" , "to" : "forum.ithomer.net" , "subject" : "ithomer.net"}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10108"} , "ranking" : 0}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10109"} , "ranking" : 1}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010a"} , "ranking" : 2}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010b"} , "ranking" : 3}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010c"} , "ranking" : 4}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010d"} , "ranking" : 5}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010e"} , "ranking" : 6}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010f"} , "ranking" : 7}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10110"} , "ranking" : 8}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10111"} , "ranking" : 9}
collection find({"ranking":1}):
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10109"} , "ranking" : 1}
collection find({"ranking":[5-9)}):
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010d"} , "ranking" : 5}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010e"} , "ranking" : 6}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010f"} , "ranking" : 7}
{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10110"} , "ranking" : 8}

mongodb數組樣本:

複製代碼 代碼如下:

 @SuppressWarnings("unchecked")
 public static void loadMediaTags(List<MediaEntity> mediaEntityList) {
  mediaEntityList.clear();

  try {
   Mongo mongo = new Mongo(CosineCluster.gMongo_HOST, CosineCluster.gMongo_PORT);
   DB db = mongo.getDB(CosineCluster.gMongo_DB);
   DBCollection collection = db.getCollection(CosineCluster.gMongo_Coll_Media);

   DBCursor cursor = collection.find();
   int index = 0;
   long startTime = System.currentTimeMillis();
   while(cursor.hasNext()){
    BasicDBObject obj = (BasicDBObject) cursor.next();

    long id = obj.getLong("_id");
    ArrayList<String> tagList = (ArrayList<String>) obj.get("tag");     // tag
    ArrayList<String> keywordList = (ArrayList<String>)obj.get("keyword");   // keyword
    ArrayList<Integer> copyrightList = (ArrayList<Integer>)obj.get("copyright"); // copyright

  
    MediaEntity mediaEntity = new MediaEntity();

    mediaEntity.setId(id);

    // tag
    for(int j=0; j<tagList.size(); j++) {
     mediaEntity.addTag(tagList.get(j));
     int tagId = getTagInt(tagList.get(j));
     mediaEntity.addTag(tagId);
    }

    // actors
    ArrayList<DBObject> actorsObjList = (ArrayList<DBObject>)obj.get("actors");  // actors
    for(int j=0; j<actorsObjList.size(); j++) {
      mediaEntity.addActor((String) actorsObjList.get(j).get("name")); 
      int actorId = getActorInt((String)actorsObjList.get(j).get("name"));
      mediaEntity.addActor(actorId);
    }

    // director
    ArrayList<DBObject> directorObjList = (ArrayList<DBObject>)obj.get("director"); // director
    for(int j=0; j<directorObjList.size(); j++) {
      mediaEntity.addDirector((String) directorObjList.get(j).get("name")); 
      int directorId = getDirectorInt((String) directorObjList.get(j).get("name"));
      mediaEntity.addDirector(directorId);
    }

    // keyword
    for(int j=0; j<keywordList.size(); j++) {
     mediaEntity.addKeyword(keywordList.get(j));
     int keywordId = getKeywordInt(keywordList.get(j));
     mediaEntity.addKeyword(keywordId);
    }

    // copyright
    for(int j=0; j<copyrightList.size(); j++) {
     mediaEntity.addCopyright(copyrightList.get(j));
    }

    mediaEntityList.add(mediaEntity);

    index++;
    if(index > 100) {
     break;
    }
    System.out.println(index + " --- mediaEntity : " + mediaEntity.toString());
   }
   long costTime = System.currentTimeMillis() - startTime;
   System.out.println("load data costTime = " + index + "; costTime = " + costTime/1000f);

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static int getTagInt(String tag) {
  int tagIntId = -1;

  try {
   MongoClient mongo = new MongoClient(CosineCluster.gMongo_HOST, CosineCluster.gMongo_PORT);
   DB db = mongo.getDB(CosineCluster.gMongo_DB);
   DBCollection tagmapCollection = db.getCollection("recommend_tag_map");

   DBCursor cursor = tagmapCollection.find(new BasicDBObject("name", tag)); 
   if(cursor == null || cursor.toArray().size() <= 0) {  // 處理小於2或n的映射關鍵字,下同
    return tagIntId;
   }
   DBObject obj = cursor.toArray().get(0);

   
   String name = tag;
   tagIntId = (Integer) obj.get("id");
   int num = (Integer) obj.get("num");

   mongo.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }

  return tagIntId;
 }

 public static int getActorInt(String actor) {
  int actorIntId = -1;
  try {
   MongoClient mongo = new MongoClient(CosineCluster.gMongo_HOST, CosineCluster.gMongo_PORT);
   DB db = mongo.getDB(CosineCluster.gMongo_DB);
   DBCollection tagmapCollection = db.getCollection("recommend_actor_map");

   DBCursor cursor = tagmapCollection.find(new BasicDBObject("name", actor));
   if(cursor == null || cursor.toArray().size() <= 0) {
    return actorIntId;
   }
   DBObject obj = cursor.toArray().get(0);

   String name = actor;
   actorIntId = (Integer) obj.get("id");
   int num = (Integer) obj.get("num");

   mongo.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }

  return actorIntId;
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.