文档章节

MongoDB Java Tutorial

abcijkxyz
 abcijkxyz
发布于 2016/07/08 16:30
字数 1471
阅读 1
收藏 0
点赞 0
评论 0

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.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
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;


MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, supply a seed list of members
MongoClient mongoClient = new MongoClient(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 MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.  See the concurrency doc page for more information.

The MongoClient 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 MonglClient instances, note that:

  • all resource usage limits (max connections, etc) apply per MongoClient instance
  • to dispose of an instance, make sure you call MongoClient.close() to clean up resources

Note: The MongoClient class is new in version 2.10.0. For releases prior to that, please use the Mongo class instead.

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 a MongoClient instance:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
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

name
address

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

Setting write concern

As of version 2.10.0, the default write concern is WriteConcern.ACKNOWLEDGED, but it can be easily changed:

m.setWriteConcern(WriteConcern.JOURNALED);

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.

Note: Prior to version 2.10.0, the default write concern is WriteConcern.NORMAL. Under normal circumstances, clients will typically change this to ensure they are notified of problems writing to the database.

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("name", "MongoDB").
                                       append("type", "database").
                                       append("count", 1)
                                      .append("info", new BasicDBObject("x", 203).append("y", 102));

        coll.insert(doc);
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

{
   "i" : value
}

and we can do this fairly efficiently in a loop

for (int i=0; i < 100; i++) {
    coll.insert(new BasicDBObject("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("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("j", new BasicDBObject("$ne", 3).
                                               append("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("i", new BasicDBObject("$gt", 50));  // e.g. find all where i > 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("i", new BasicDBObject("$gt", 20).
                                                        append("$lte", 30));  // i.e.   20 < i <= 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));  // create index on "i", ascending
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:

MongoClient mongoClient = new MongoClient();

        for (String s : m.getDatabaseNames()) {
            System.out.println(s);
        }
Dropping A Database

You can drop a database by name using a MongoClient instance:

MongoClient mongoClient = new MongoClient();
mongoClient.dropDatabase("myDatabase");

本文转载自:http://blog.csdn.net/yuwenruli/article/details/8498766

共有 人打赏支持
abcijkxyz
粉丝 60
博文 6196
码字总数 1876
作品 0
深圳
项目经理
Java MongoDB : Save image example

Java MongoDB : Save image example In this tutorial, we show you how to save an image file into MongoDB, via GridFS API. The GridFS APIs are able to serve other binary files as w......

引鸩怼孑
2015/05/22
0
0
MongoDB 基本操作与MongoDB for JAVA

一、准备工作 1、 下载mongoDB 下载地址:http://www.mongodb.org/downloads 选择合适你的版本 相关文档:http://www.mongodb.org/display/DOCS/Tutorial 2、 安装mongoDB A、 不解压模式: ...

IT_小翼
2013/08/07
0
1
MongoDB在spring中xml传统配置

背景 旧项目中依然在使用springmvc的xml传统配置,最近需要使用MongoDB,需要在spring引入MongoDB的连接配置。 解决 配置mongodb数据库 配置mongodb数据工厂 配置mongodb的Template 配置mon...

亚林瓜子
06/12
0
0
【MongoDB for Java】Java操作MongoDB

开发环境: System:Windows IDE:eclipse、MyEclipse 8 Database:mongoDB 开发依赖库: JavaEE5、mongo-2.5.3.jar、junit-4.8.2.jar Email:hoojo_@126.com Blog:http://blog.csdn.net/IB......

underA
2013/05/15
0
0
spring MVC 整合mongodb

Spring Mongodb 目录 1 SPRING整合MONGODB 1 1.1 环境准备 1 1.2 包依赖 1 1.3 配置 2 2 案列 5 2.1 SPRING MVC整合MONGODB代码案例 5 1 Spring整合Mongodb 1.1 环境准备 1. mongodb官网 ht...

浅夏
2014/03/13
0
0
[翻译官方文档]Java Tutorial(Java操作MongoDB入门)

Java Tutorial(Java操作MongoDB入门) Introduction 介绍 This page is a brief overview of working with the MongoDB Java Driver. 这是使用MongoDB java驱动的简单说明。 For more infor......

noday
2011/06/30
0
12
Spring从MongoDB中下载文件之GridFS

问题 之前提到过以GridFS方式上传问题到MongoDB中:Spring保存文件到MongoDB之GridFS支持。现在需要从Mongodb中读取文件,应该怎么处理类? 解决 Maven 注解mongoDbFactory 获取文件流 Note...

亚林瓜子
06/12
0
0
Linux环境下将log4j的日志存储到mongoDB

单位有很多java项目,一般上生产的项目日志都是通过log4j打印在本地,平常开发同学要查看日志还要给他们开个专门的FTP,不利于集中维护管理,近日因工作需要,在网上看到相关技术资料,可把l...

基督山伯爵
2013/03/04
0
3
MyCAT SQL ON MongoDB

概述 可能你在看到这个标题会小小的吃惊,MyCAT 能使用 MongoDB 做数据节点。是的,没错,确实可以。 吼吼吼,让我们开启这段神奇的“旅途”。 本文主要分成四部分: 总体流程,让你有个整体...

wangchen1999
05/02
0
0
waylau/new-star-blog

NewStarBlog NewStarBlog is an open source Java blog platform. NewStarBlog 是开源 Java 博客平台。 Technologies 涉及技术 NewStarBlog covers Spring Framework 5, Spring Boot 2, Thym......

waylau
04/26
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

用 Python 实现打飞机,让子弹飞吧!

所用技术和软件 python 2.7 pygame 1.9.3 pyCharm 准备工作 安装好 pygame 在第一次使用 pygame 的时候,pyCharm 会自动 install pygame。 下载好使用的素材。 技术实现 初始化 pygame 首先要...

猫咪编程
7分钟前
0
0
MySQL的行锁和表锁

简单总结一下行锁和表锁。 行锁 每次操作锁住一行数据。开销大,加锁慢;会出现死锁;锁定粒度最小,发生锁冲突的概率最低,并发度也最高。 表锁 每次操作锁住整张表。开销小,加锁快;不会出...

to_ln
9分钟前
0
0
Java IO类库之字节数组输入流ByteArrayInputStream

一、ByteArrayInputStream字节数组输入流介绍 ByteArrayInputStream是字节数组输入流,继承自InputStream。它的内部包含一个缓冲区,是一个字节数组,缓冲数组用于保存从流中读取的字节数据,...

老韭菜
11分钟前
0
0
iOS安全应该做哪些事情

1. 尽量使用HTTPS协议。 2. 密码提交的时候,密码使用SHA256加密后传输,MD5等经过哈希碰撞已经可以推算出原文。 3. 密码提交的时候,可以加盐。 4. 密码保存在本地的时候,尽量使用钥匙串保...

HOrange
17分钟前
0
0
react native 注意事项

1. 环境参考官网 android studio 必装 java jdk安装 1.8版本(环境建议自己一步一步配置,切记不要 apt ) 2.有改变编译内容发现 会白屏,然后APP消失,请卸载原来的测试 appinfo (连续两次...

304158
23分钟前
0
0
FOMO游戏代码解析

源代码在此处

怎当她临去时秋波那一转
28分钟前
1
0
EOS智能合约与DApp开发入门

EOS的是Block.One主导研发的一个区块链底层公链系统,它专门为支撑商业去中心化 应用(Decentralized Application)而设计,其代码开源。 比特币被称为区块链1.0,因为它开辟了数字加密货币的...

笔阁
41分钟前
1
0
编译cjson到dll

https://blog.csdn.net/mengzhisuoliu/article/details/52203724 编译完成后 是纯lua实现的json decode 的10倍以上...

梦想游戏人
51分钟前
0
0
JS基础- Date 对象

Date 对象 Date 对象用于处理日期和时间。 创建 Date 对象的语法: var myDate=new Date() 注释:Date 对象会自动把当前日期和时间保存为其初始值。 Date 对象属性 属性 描述 constructor 返...

ZHAO_JH
53分钟前
0
0
Python数据分析numpy(1)

Python开源的科学计算基础库 1.表示N维数组对象ndarray 2.线性代数、傅里叶变换、随机数生成 3.广播函数,整合c++、c 一.数据的维度 1.数据 2.数据维度 3.一维数据 (1)特点 (2)Python中的...

十年磨一剑3344
56分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部