欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java操作mongodb示例分享

程序员文章站 2024-02-25 20:52:54
复制代码 代码如下:package mymaven;  import java.net.unknownhostexception;  import ja...

复制代码 代码如下:

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;
 }