技术开发 频道

Java Tutorial:Java操作MongoDB入门

  【IT168 技术】个人编译能力有限,以下提供英汉对照,欢迎讨论指正。

  Introduction

  介绍

  This page is a brief overview of working with the MongoDB Java Driver.

  这是使用MongoDB java驱动的简单说明。

  For more information about the Java API, please refer to the online API Documentation for Java Driver

  想获取更多关于java的API,请查看在线API文档。

  A Quick Tour

  Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath. The following code snippets come from the examples/QuickTour.java example code found in the driver.

  使用很简单。首先将驱动mongo.jar放入classpath。下面的代码段是驱动中例子examples/QuickTour.java中的内容

  Making A Connection

  创建连接

  To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to. The database doesn't have to exist - if it doesn't, MongoDB will create it for you.

  创建连接至少需要你要连接的数据库名。如果数据库不存在,MongoDB会自动创建。

  Additionally, you can specify the server address and port when connecting. The following example shows three ways to connect to the database mydb on the local machine :

  此外,你还可以指定数据库服务器地址和端口。下边的例子中有三种连接本机mydb数据库方法:

import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
Mongo m
= new Mongo();
// or
Mongo m = new Mongo( "localhost" );
// or
Mongo m = new Mongo( "localhost" , 27017 );
DB db
= m.getDB( "mydb" );

  At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations.

  db对象就是连接服务器中指定数据库的连接。使用他你可以做很多操作。

  Note: The Mongo object instance actually represents a pool of connections to the database; you will only need one object of class Mongo even with multiple threads. See the concurrency doc page for more information.

  注意:Mongo的实例是数据库连接池;在多个线程中只需要一个实例。更多的介绍请参考concurrency文档。

  The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given DB cluster and use it across your app. If for some reason you decide to create many mongo intances, note that:

  Mongo类是线程安全和共享的。可以在整个应用中使用他。如果你想创建多个Mongo实例,注意:

  all resource usage limits (max connections, etc) apply per mongo instance.

  每个mongo实例的资源使用限制。

  to dispose of an instance, make sure you call mongo.close() to clean up resources.

  记得使用mongo.close()关闭资源。

0
相关文章