从mongodb官网复制的,看起来方便点...
http://www.mongodb.org/display/DOCS/Java+Tutorial
Introduction
This page is a brief overview of working with the MongoDB Java Driver.
For more information about the Java API, please refer to the online API Documentation for Java Driver
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.
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.
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 :
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
Mongo m = new Mongo();
Mongo m = new Mongo( "localhost" );
Mongo m = new Mongo( "localhost" , 27017 );
Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
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.
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.
The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application. If for some reason you decide to create many mongo instances, note that:
- all resource usage limits (max connections, etc) apply per mongo instance
- to dispose of an instance, make sure you call mongo.close() to clean up resources
Authentication (Optional)
MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with the connected mongo object :
boolean auth = db.authenticate(myUserName, myPassword);
If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.
Most users run MongoDB without authentication in a trusted environment.
Getting A List Of Collections
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
and assuming that there are two collections, name and address, in the database, you would see
as the output.
Getting A Collection
To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
DBCollection coll = db.getCollection("testCollection")
Once you have this collection object, you can now do things like insert data, query for data, etc
Inserting a Document
Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x : 203,
y : 102
}
}
Notice that the above has an "inner" document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.
BasicDBObject doc = new BasicDBObject();
doc.put("name", "MongoDB");
doc.put("type", "database");
doc.put("count", 1);
BasicDBObject info = new BasicDBObject();
info.put("x", 203);
info.put("y", 102);
doc.put("info", info);
coll.insert(doc);
Setting write concern
For typical usage, you should set the default write concern to ensure that your application will
be notified if the server is unable to complete an update operation.
m.setWriteConcern(WriteConcern.SAFE);
There are many options for write concern. Additionally, the default write concern can be overridden on the database, collection, and individual update operations. Please consult the API Documentation for details.
Finding the First Document In A Collection using findOne()
To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
and you should see
{ "_id" : "49902cde5162504500b45c2c" , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
Note the _id element has been added automatically by MongoDB to your document. Remember, MongoDB reserves element names that start with "_"/"$" for internal use.
Adding Multiple Documents
In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be
and we can do this fairly efficiently in a loop
for (int i=0; i < 100; i++) {
coll.insert(new BasicDBObject().append("i", i));
}
Notice that we can insert documents of different "shapes" into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free"
Counting Documents in A Collection
Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using thegetCount() method.
System.out.println(coll.getCount());
and it should print 101.
Using a Cursor to Get All the Documents
In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
and that should print all 101 documents in the collection.
Getting A Single Document with A Query
We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;
BasicDBObject query = new BasicDBObject();
query.put("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
and it should just print just one document
{ "_id" : "49903677516250c1008d624e" , "i" : 71 }
You may commonly see examples and documentation in MongoDB which use $ Operators, such as this:
db.things.find({j: {$ne: 3}, k: {$gt: 10} });
These are represented as regular String keys in the Java driver, using embedded DBObjects:
BasicDBObject query = new BasicDBObject();
query.put("j", new BasicDBObject("$ne", 3));
query.put("k", new BasicDBObject("$gt", 10));
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Getting A Set of Documents With a Query
We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write :
query = new BasicDBObject();
query.put("i", new BasicDBObject("$gt", 50));
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
which should print the documents where i > 50. We could also get a range, say 20 < i <= 30 :
query = new BasicDBObject();
query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Creating An Index
MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the "i" field :
coll.createIndex(new BasicDBObject("i", 1));
Getting a List of Indexes on a Collection
You can get a list of the indexes on a collection :
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
and you should see something like
{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} }
Quick Tour of the Administrative Functions
Getting A List of Databases
You can get a list of the available databases:
Mongo m = new Mongo();
for (String s : m.getDatabaseNames()) {
System.out.println(s);
}
Dropping A Database
You can drop a database by name using the Mongo object:
m.dropDatabase("my_new_db");
分享到:
相关推荐
MongoDB Async Java Driver Documentation Welcome to the MongoDB Async Java driver documentation hub. Getting Started The Getting Started guide contains installation instructions and a simple ...
在"springboot-angular-mongodb-crud-tutorial-master"压缩包中,你可能找到以下主要文件夹和文件: 1. `backend` - 包含Spring Boot项目的源代码,包括实体类、配置、控制器等。 2. `frontend` - 包含Angular项目的...
要求Java-1.8.x Maven-3.xx MongoDB-3.xx设定步骤1.克隆应用程序git clone https://github.com/callicoder/spring-boot-mongodb-angular-todo-app.git 2.使用maven构建并运行后端应用程序cd spring-boot-backendmvn ...
MBallem | 用Java编程 Java中的MongoDB和持久性教程 发布教程的项目源-使用MongoDB的NoSQL和Java的持久性-发布在: : Mongo Java驱动程序版本:2.10.1
这是一个基于Spring Boot、MongoDB和Angular 5的Java Web应用程序示例,用于展示CRUD(创建、读取、更新和删除)操作。这个项目旨在帮助开发者理解如何将这些技术集成到一个完整的Web应用中。 首先,Spring Boot是...
构建Spring Boot,MongoDB和React.js CRUD Web应用程序 此源代码是教程的一部分。 要在本地运行: 运行MongoDB服务器 克隆此存储库 在前端目录中,运行npm install和npm run build 从根目录运行./gradlew bootRun
Java Tutorial:Java操作MongoDB入门
- **核心Java**:熟悉Java语言的基本概念和编程技巧。 - **数据库概念**:理解数据库管理和操作的基本原理。 - **Linux操作系统**:具备基本的Linux命令行操作能力。 ### 版权声明与免责声明 本教程版权所有归...
"fullstack-tutorial-master" 文件可能是项目主分支的源代码,包含了上述所有技术的示例和教程。通过这个项目,你可以学习到如何从零开始搭建一个全功能的Web应用,同时熟悉开发流程和最佳实践。无论是个人学习还是...
- **JVMLanguages**:Java 虚拟机语言支持。 - **Python Language Center**:Python 驱动程序文档。 综上所述,MongoDB 的官方文档非常详尽,几乎覆盖了所有方面,无论是初学者还是有经验的开发者都能从中受益。...
Spring Boot,安全性和数据MongoDB身份验证示例本教程是要在本地运行: 克隆此仓库在另一个选项卡mongod运行MongoDB守护程序构建此源./gradlew build 运行此应用程序./gradlew bootRun
3. **Java 教程**:[http://www.mongodb.org/display/DOCS/Java+Tutorial](http://www.mongodb.org/display/DOCS/Java+Tutorial) #### 六、结语 本 MongoDB Cheat Sheet v1.0 包含了 MongoDB 基础操作的重要知识点...
#Tutorial for Spring Boot、Spring Data for Mongo 和 Vaadin 使用 Java 7 需要一个本地mongodb来测试 创建一个数据库“测试” 创建一个集合“国家” 导入/resources/mongo/countries.json 下的示例数据 跑步 ....
6. **数据访问**:掌握如何与各种数据库(如MySQL、PostgreSQL、MongoDB等)集成,使用JPA或MyBatis进行数据操作。 7. **Actuator**:理解Spring Boot Actuator提供的健康检查、指标监控、审计日志等功能,用于生产...
- **Drivers**:详细列出了支持MongoDB的各种语言驱动程序,包括C、C#、Java、Python、PHP等。 - **Driver Syntax Table**:给出了不同语言驱动的语法对照表,方便开发者跨语言迁移。 #### 九、内部原理与实现细节 ...
教程wk9:MongoDB 本教程的起点是用户管理教程的解决方案。 在该教程中,我们有一个UserService将用户数据存储在内存中。 在本教程中,我们将其放入数据库中。 由于我们的条款还很晚,解决方案将立即发布-您可以...
MongoDB支持多种编程语言,提供了丰富的驱动程序库,包括但不限于Java、Node.js、Ruby等,便于不同语言背景的开发者使用MongoDB。 ### **19. MongoDB管理指南(Mongo Administration Guide)** MongoDB管理指南涵盖...
【HTML】标签是Web开发的基础,它代表了超文本标记语言(HyperText Markup ...这个“web-dev-tutorial”短期课程将引导你逐步踏入这个充满活力的领域,通过理论学习和实践操作,掌握成为一名合格Web开发者所需的技能。
文档中提供了各种语言的驱动程序使用教程,例如“CSharpDriverQuickstart”、“Python Tutorial”和“Ruby Tutorial”,这些教程涵盖了从基本连接到高级功能的使用方法,是开发人员学习和应用MongoDB的重要资源。...
"ecommerce-tutorial-planning"项目旨在为初学者提供一个逐步学习电子商务系统开发的框架。在这个项目中,我们将涵盖从需求分析到系统实现的整个过程,确保你能够掌握核心的Java编程技能以及电子商务系统设计的关键...