mongodb进行java调用方法

http://blog.csdn.net/qew110123/article/details/46535103

</pre>进行mongodb数据的简单操作的单利模式的处理(此案例是网上找的,项目中不可能使用该方法,都会是数据库连接池的)<p></p><p></p><pre name="code" class="java">//实例化Mongo对象,连接27017端口
            Mongo mongo = new Mongo("localhost", 27017);
                               //连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
            DB db = mongo.getDB("yourdb");
            // Get collection from MongoDB, database named "yourDB"
//从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立
            DBCollection collection = db.getCollection("yourCollection");
    // 使用BasicDBObject对象创建一个mongodb的document,并给予赋值。
            BasicDBObject document = new BasicDBObject();
            document.put("id", 1001);
            document.put("msg", "hello world mongoDB in Java");
            //将新建立的document保存到collection中去
            collection.insert(document);
            // 创建要查询的document
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("id", 1001);
            // 使用collection的find方法查找document
            DBCursor cursor = collection.find(searchQuery);
            //循环输出结果
            while (cursor.hasNext()) {
            System.out.println(cursor.next());
            }
            System.out.println("Done"); 

连接数据的案例在https://git.oschina.net/zongtui/zongtui-filter/commit/ffeace115d006bd252ae7aaae0d60428bd52662b#diff-7

其中使用文件为

9 个文件发生了变化

 filter/config/config.xml(进行配置xml文件,进行配置mongodb的ip,端口号和数据库表的名称)
 filter/lib/dom4j-1.6.1.jar
 filter/lib/jaxen-1.1.1.jar
 filter/lib/junit.jar
 filter/lib/log4j-over-slf4j-1.6.4.jar
 filter/lib/mongo-java-driver-2.12.1.jar(调用的包)
 filter/src/main/java/com/zongtui/filter/config/ConfigManager.java(读取xml中的文件)
 filter/src/main/java/com/zongtui/filter/mongo/MongoDB.java(调用的模板)
 filter/src/main/java/com/zongtui/filter/mongodb/MongoDbConn.java(进行数据库连接池的搭建)


结下了是数据库的真正使用的方法。

进行mongodb数据库连接池的定义。

MongoDbConn.java
package com.zongtui.filter.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.zongtui.filter.config.ConfigManager;

public class MongoDbConn
{
  private static MongoDbConn instance = null;

  private String host = null;
  private int port = 0;
  private List<ServerAddress> replSet = null;
  private MongoOptions options = null;
  private String database = null;
  private String username = null;
  private String password = null;
  private Mongo mongo = null;
  private DB db = null;

  private MongoDbConn()
  {
    this.host = ConfigManager.getInstance().getConfigValue("db_ip");
    this.port = Integer.valueOf(ConfigManager.getInstance().getConfigValue("db_port")).intValue();
    this.database = ConfigManager.getInstance().getConfigValue("db_name");
//    this.host = "192.168.184.130";
//    this.port = 27017;
//    this.database = "nutch";
// (续上)此处我用的通过xml文件进行数据的读取,可以通过直接写入的方式进行数据的操作,二次进行数据的编写。
    
  }

  public static MongoDbConn getInstance()
  {
    if (instance == null) {
      instance = new MongoDbConn();
    }
    return instance;
  }

  public void init(String database)
  {
    this.database = database;
  }

  public void init(String host, int port, String database) {
    this.host = host;
    this.port = port;
    this.database = database;
  }

  public void init(String host, int port, String database, String username, String password) {
    this.host = host;
    this.port = port;
    this.database = database;
    this.username = username;
    this.password = password;
  }

  public void init(List<ServerAddress> replSet, String database) {
    this.replSet = replSet;
    this.database = database;
  }

  public void init(List<ServerAddress> replSet, String database, String username, String password) {
    this.replSet = replSet;
    this.database = database;
    this.username = username;
    this.password = password;
  }

  public MongoOptions getOptions() {
    return this.options;
  }

  public void setOptions(MongoOptions options) {
    this.options = options;
  }

  private void connect()
  {
    try
    {
      if ((this.host != null) && (this.port != 0))
      {
        ServerAddress address = new ServerAddress(this.host, this.port);

        if (this.options != null)
          this.mongo = new Mongo(address, this.options);
        else {
          this.mongo = new Mongo(address);
        }
      }
      else if (this.replSet != null)
      {
        if (this.options != null)
          this.mongo = new Mongo(this.replSet, this.options);
        else {
          this.mongo = new Mongo(this.replSet);
        }

      }

      if (this.mongo != null)
        this.db = this.mongo.getDB(this.database);
      else {
    	  System.out.println("无法取得数据库实例,请确认配置信息");
//        SystemLog.getInstance().showMsg("无法取得数据库实例,请确认配置信息");
      }

      if ((this.username != null) && (this.password != null))
        if (this.db.authenticate(this.username, this.password.toCharArray())) {
        	System.out.println("登陆成功:" + this.username);
//          SystemLog.getInstance().showMsg("登陆成功:" + this.username);
        } else {
          this.db = null;
          System.out.println("登陆失败:" + this.username);
//          SystemLog.getInstance().showMsg("登陆失败:" + this.username);
        }
    }
    catch (UnknownHostException e)
    {
//      SystemLog.getInstance().showMsg("数据库地址错误");
    	System.out.println("数据库地址错误");
      e.printStackTrace();
    }
  }

  public DB getDBConnection()
  {
    if (this.db == null) {
      connect();
    }

    return this.db;
  }
}

进行mongodb数据的操作

package com.zongtui.filter.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.zongtui.filter.config.ConfigManager;

public class MongoDbConn
{
  private static MongoDbConn instance = null;

  private String host = null;
  private int port = 0;
  private List<ServerAddress> replSet = null;
  private MongoOptions options = null;
  private String database = null;
  private String username = null;
  private String password = null;
  private Mongo mongo = null;
  private DB db = null;

  private MongoDbConn()
  {
    this.host = ConfigManager.getInstance().getConfigValue("db_ip");
    this.port = Integer.valueOf(ConfigManager.getInstance().getConfigValue("db_port")).intValue();
    this.database = ConfigManager.getInstance().getConfigValue("db_name");
//    this.host = "192.168.184.130";
//    this.port = 27017;
//    this.database = "nutch";
    
  }

  public static MongoDbConn getInstance()
  {
    if (instance == null) {
      instance = new MongoDbConn();
    }
    return instance;
  }

  public void init(String database)
  {
    this.database = database;
  }

  public void init(String host, int port, String database) {
    this.host = host;
    this.port = port;
    this.database = database;
  }

  public void init(String host, int port, String database, String username, String password) {
    this.host = host;
    this.port = port;
    this.database = database;
    this.username = username;
    this.password = password;
  }

  public void init(List<ServerAddress> replSet, String database) {
    this.replSet = replSet;
    this.database = database;
  }

  public void init(List<ServerAddress> replSet, String database, String username, String password) {
    this.replSet = replSet;
    this.database = database;
    this.username = username;
    this.password = password;
  }

  public MongoOptions getOptions() {
    return this.options;
  }

  public void setOptions(MongoOptions options) {
    this.options = options;
  }

  private void connect()
  {
    try
    {
      if ((this.host != null) && (this.port != 0))
      {
        ServerAddress address = new ServerAddress(this.host, this.port);

        if (this.options != null)
          this.mongo = new Mongo(address, this.options);
        else {
          this.mongo = new Mongo(address);
        }
      }
      else if (this.replSet != null)
      {
        if (this.options != null)
          this.mongo = new Mongo(this.replSet, this.options);
        else {
          this.mongo = new Mongo(this.replSet);
        }

      }

      if (this.mongo != null)
        this.db = this.mongo.getDB(this.database);
      else {
    	  System.out.println("无法取得数据库实例,请确认配置信息");
//        SystemLog.getInstance().showMsg("无法取得数据库实例,请确认配置信息");
      }

      if ((this.username != null) && (this.password != null))
        if (this.db.authenticate(this.username, this.password.toCharArray())) {
        	System.out.println("登陆成功:" + this.username);
//          SystemLog.getInstance().showMsg("登陆成功:" + this.username);
        } else {
          this.db = null;
          System.out.println("登陆失败:" + this.username);
//          SystemLog.getInstance().showMsg("登陆失败:" + this.username);
        }
    }
    catch (UnknownHostException e)
    {
//      SystemLog.getInstance().showMsg("数据库地址错误");
    	System.out.println("数据库地址错误");
      e.printStackTrace();
    }
  }

  public DB getDBConnection()
  {
    if (this.db == null) {
      connect();
    }

    return this.db;
  }
}

在程序中进行xml进行数据操作,可以上

http://blog.csdn.net/qew110123/article/details/46535103

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是MongoDBJava调用代码示例: 1.导入MongoDB Java驱动程序 在您的Java项目中,您需要导入MongoDB Java驱动程序。您可以通过Maven或手动下载并在您的项目中添加JAR文件来完成此操作。例如,如果您使用Maven,则可以将以下依赖项添加到您的pom.xml文件中: ``` <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.7</version> </dependency> ``` 2.连接到MongoDB 在您的Java代码中,您需要创建一个MongoClient对象来连接到MongoDB。以下是一个简单的示例: ``` import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoDBExample { public static void main(String[] args) { MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydb"); System.out.println("Connected to MongoDB!"); } } ``` 这将连接到名为“mydb”的MongoDB数据库。如果您的MongoDB服务器在本地主机上运行,并且端口号为27017,则以下行将连接到MongoDB: ``` MongoClient mongoClient = new MongoClient("localhost", 27017); ``` 3.插入文档 在MongoDB中,您可以将数据存储在文档中。以下是向MongoDB插入新文档的示例: ``` import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBExample { public static void main(String[] args) { MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> collection = database.getCollection("mycollection"); Document doc = new Document("name", "John Doe") .append("age", 30) .append("email", "johndoe@example.com"); collection.insertOne(doc); System.out.println("Document inserted successfully!"); } } ``` 这将向名为“mycollection”的MongoDB集合插入一个新文档。 4.查询文档 可以使用MongoDB Java驱动程序来查询MongoDB文档。以下是一个简单的示例: ``` import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class MongoDBExample { public static void main(String[] args) { MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> collection = database.getCollection("mycollection"); Document query = new Document("name", "John Doe"); MongoCursor<Document> cursor = collection.find(query).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } } ``` 这将查询名为“mycollection”的MongoDB集合中的所有文档,其中字段“name”等于“John Doe”。 这是MongoDBJava调用代码示例。您可以通过使用MongoDB Java驱动程序来执行各种操作,例如插入,查询,更新和删除MongoDB文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值