Mongodb的安装以及Java连接Mongodb初探

一、MongoDB的下载与安装

        文件名:mongodb-linux-x86_64-2.4.7.tgz

        下载地址:http://pan.baidu.com/s/1kT5tu

        系统环境:Centos-6.3

        解压:tar -zvxf mongodb-linux-x86_64-2.4.7.tgz , 里面最重要的就是bin目录,不需要安装直接启动mongod就可以了

        将该bin目录加入环境变量:

                vi /etc/profile

                export PATH=$PATH:/home/houqd/mongodb2.4.7/bin

                 source /etc/profile

         直接运行mongod启动MongoDB数据库,这里可能会报如下的错误:


      这里的原因是因为:MongoDB在启动的时候,默认在目录/data/db(Windows上是c:\data\db)下存储数据文件,可以使用dbpath选项指定一个不通的数据目录:

mongod --dbpath   /youselfpath , 如果数据目录不存在,要先创建好,还要确保mongod拥有该目录的写权限。

     创建目录/data/db,然后启动mongod,看到如下信息:

     

    可以看到Mongodb成功启动,并且监听27017端口。这个端口可以用来我们利用编程语言连接Mongodb数据库。

二、基本操作介绍

     这里我们先要理解Mongodb中的三个称谓:数据库(db),可以按关系型数据库中的数据库来理解;集合(Collection),可以按关系型数据库中的表来理解;文档(Document)可以按关系型数据库中的行记录来理解。这里要分清关系型数据库和文档数据库在存储时的区别,关系型数据库假定数据的结构已经明确定义,数据是致密的,并且很大程度上是一致的,比如存储关于用户的一条数据,你定义了users表,其中有username , address , age 等等一些列字段,你所有要存入表中的数据,都必须按照这几个字段来存入,而不管某记录在某个字段是否有值,是否有存储的必要。而文档型数据库Mongodb则不然,它对数据的定义是松散的,某记录的某个值我可以随意定义存或不存,而不用担心某个字段没有值造成数据不统一。下面举个例子来说明:建立数据库prefs,向里面插入几条数据:

     use prefs;

     a={name:"houqd" , where:"beijing"};

     b={name:"zhangsan" , where:"suzhou"}

     c={name:"lisi" , where:"suzhou" , age:22}

     d={name:"lisi" , where:"suzhou" , age:22 ,sex:"man" }

     db.location.save(a);

     db.location.save(b);

     db.location.save(c);

     db.location.save(d);

     这样,数据存储就准备好了。这里有几点需要注意:use prefs命令将当前数据库改变为perfs数据库,但是数据库本身一直都没有显示的创建过。同样,通过传递每条数据给db.location.save()方法将数据写入location集合,但是集合也没有显示的创建过。在MongoDB中,数据库和集合都是在插入数据时才创建。因此,在上面创建是发生在插入第一条数据即:db.lication.save(a)的时候。

    查看存储的内容:db.location.find();   结果如下图所示(注:数据和这里的数据不同)

                   

   接下来我们就可以对数据进行查找了:db.location.find({name:"houqd"}) 查找出文档中所有name为houqd的文档

                                                                       db.location.find({name:"wupengqing" , age:22}) 查找出文档中name为wupengqing且年龄为22岁的文档记录

三、MongoDB Java Dirver

        MongoDB提供了提供了和编程语言之间的接口,包括:Java、PHP、Ruby和Python等,这里我们简要介绍和Java的接口

        首先需要下载MongoDB的Java驱动,下载地址:http://pan.baidu.com/s/18AddW ,文件名为:mongo-java-driver-master.zip

        官网下载链接:https://github.com/mongodb/mongo-java-driver/downloads 注意要下载和你的MongoDB版本一致的jar包

        在Eclipse中新建Java项目MongoDB,右键点击:Build Path -》Add external Archives ... -》将你下载的jar包导入,最终情况如下:

                                                                 

四、编写Java连接MongoDB的测试程序

package com.mongodb;
import java.util.Set;
import com.mongodb.Mongo ;
import com.mongodb.DB;
import java.net.UnknownHostException;

public class MongodbConTest {

	private Mongo m = null ;
	private DB db ;
	
	// 建立与Mongodb数据库的连接
	public void connect()
	{
		try{
			m = new Mongo("192.168.255.11" , 27017);
			
		}catch(UnknownHostException e){
			e.printStackTrace();			
		}catch(MongoException e){
			e.printStackTrace();
		}
	}
	
	// 列出dbName数据库中的所有集合
	public void listAllCollections(String dbName)
	{
		if(m!=null){
			db = m.getDB(dbName);
			Set<String> collections = db.getCollectionNames();
			
			for(String c : collections){
				System.out.println(c);
			}
		}
	}
	
	// 列出prefs数据库中location集合中的所有文档
	public void listLocationCollectionDocuments()
	{
		if(m!=null){
			db = m.getDB("prefs");
			DBCollection collection = db.getCollection("location");
			
			DBCursor cur = collection.find();
			
			while(cur.hasNext())
			{
				System.out.println(cur.next());
			}
		}else{
			System.out.println("Please connect to MongoDB and then fetch the collection");
		}
	}
	
	public static void main(String[] args)
	{
		MongodbConTest mongodb = new MongodbConTest();
		
		mongodb.connect();
		
		mongodb.listAllCollections("prefs"); 
		
		mongodb.listLocationCollectionDocuments();
	}
	
}
程序运行结果:

如上所示:数据库连接且查询成功!!

        That's all , 坚持每天的学习,加油!!

发布了122 篇原创文章 · 获赞 39 · 访问量 67万+
展开阅读全文

java项目连接mongoDB报错

08-14

在本地搭了环境,启动mongoDB数据库服务并进行了连接验证,如下: ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695838_396993.png) ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695905_168178.png) 启动eclipse,登录页面时会访问mongoDB,但总是连接超时,报错信息如下: org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73) at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1885) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1696) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1679) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:598) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:589) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:301) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:273) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByUserName(ManageUserServiceImpl.java:664) at com.jftt.wifi.action.LoginAction.login(LoginAction.java:369) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370) at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71) at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63) at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:166) at com.mongodb.operation.FindOperation.execute(FindOperation.java:394) at com.mongodb.operation.FindOperation.execute(FindOperation.java:57) at com.mongodb.Mongo.execute(Mongo.java:738) at com.mongodb.Mongo$2.execute(Mongo.java:725) at com.mongodb.DBCursor.initializeCursor(DBCursor.java:815) at com.mongodb.DBCursor.hasNext(DBCursor.java:149) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1871) ... 49 more 请问各位大侠,有碰到这样的问题么?如何解决呢? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览