`
C_J
  • 浏览: 127882 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

MongoDB on DAO with Java Language

阅读更多

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;

Mongo m = new Mongo();
Mongo m = new Mongo( "localhost" );
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. 

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.

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);
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} , "_ns" : "testCollection"}

 

Note the _id and _ns elements have 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().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 the getCount() 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 cur = coll.find();

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }

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);

        cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }

 

and it should just print just one document

{ "_id" : "49903677516250c1008d624e" , "i" : 71 , "_ns" : "testCollection"}
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));  // e.g. find all where i > 50

        cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }

 

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));  // i.e.   20 < i <= 30

        cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }

 

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} , "_ns" : "system.indexes"}

 

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 + GridFS +Java 操作Mongodb中存储的文件

    目前,Java驱动通常使用的是MongoDB Java Driver,可以在Maven仓库中找到对应的依赖,例如: ```xml &lt;groupId&gt;org.mongodb &lt;artifactId&gt;mongodb-driver-sync &lt;version&gt;4.3.0 ``` 接下来,我们需要配置MongoDB...

    Mongodb连接池for java

    标题“MongoDB连接池for Java”指的是在Java环境中,针对MongoDB数据库实现的连接池解决方案。这种解决方案通常基于特定的Java驱动程序,如MongoDB的Java驱动程序(com.mongodb.client.MongoClients),它提供了连接...

    MongoDBjava各版本驱动下载

    MongoDB Java驱动是Java开发者与MongoDB数据库交互的重要工具,它允许Java应用程序通过标准的Java API来执行查询、插入、更新和删除等操作。在Java中使用MongoDB,首先需要安装并配置对应的驱动版本,以确保与正在...

    mongoDB DAO层封装

    MongoDB DAO层封装是数据库操作的重要一环,它在应用程序与数据库之间建立了一层抽象,使得数据访问更加简便和高效。在这个项目中,我们主要基于MongoDB 3.0版本和Spring Data 1.5进行整合,实现了DAO层的封装。下面...

    mongoDB文件存储_java_MongoDB_

    在Java开发中,MongoDB常被用于处理结构化和半结构化的数据。本篇文章将深入探讨MongoDB如何进行文件存储,特别是针对大文件的处理。 首先,MongoDB提供了GridFS(Grid File System)规范,这是一个用于存储和检索...

    mongoDB java 驱动

    mongoDB java 驱动 mongoDB java 驱动 mongoDB java 驱动 mongoDB java 驱动

    mongodb安装配置及java操作mongodb

    然后,《Mongodb之java操作.doc》将详细介绍如何在Java应用程序中集成和使用MongoDB。Java驱动程序是连接MongoDB的主要方式,文档可能涵盖以下内容: 1. 添加MongoDB Java驱动程序依赖:通常通过Maven或Gradle添加`...

    MongoDB Java Driver 简单操作

    为了方便开发者使用 Java 进行开发,MongoDB 提供了官方的 Java 驱动程序(MongoDB Java Driver),使得 Java 应用能够轻松地与 MongoDB 数据库进行交互。 #### 二、基本概念与连接 在开始使用 MongoDB Java Driver...

    MongoDB(4) java api

    在Java开发中,MongoDB提供了Java驱动程序,使得开发者能够方便地通过Java API来操作MongoDB数据库。这篇博客将深入探讨在Java中使用MongoDB API的主要概念和操作。 首先,我们需要在项目中引入MongoDB Java驱动...

    mongodb_java_2.6_API

    本篇将深入探讨"mongodb_java_2.6_API",即MongoDB 2.6版本的Java驱动程序API,了解如何使用Java进行MongoDB的开发。 1. **MongoDB Java驱动程序概述** MongoDB的Java驱动程序是Java开发者与MongoDB服务器通信的...

    java操作mongodb存储文件实例

    将一系列图片文件存储到MongoDB中 java操作mongodb存储文件

    java+MongoDB实现存图片、下载图片的方法示例

    "java+MongoDB实现存图片、下载图片的方法示例" 本文主要介绍了使用java和MongoDB实现存图片和下载图片的方法,并结合实例形式详细分析了java结合MongoDB实现图片的存储和下载相关操作技巧。 Java和MongoDB简介 ...

    MongoDB、Java与对象关系映射

    ### MongoDB、Java与对象关系映射 #### MongoDB简介与特性 MongoDB作为一种强大的NoSQL数据库,在处理非结构化数据方面有着显著的优势。它通过使用JSON(JavaScript Object Notation)格式来存储和检索数据,简化...

    MongoDB之Java使用例子

    在这个“MongoDB之Java使用例子”中,我们将深入探讨如何在Java环境中操作MongoDB数据库,包括增、删、改、查(CRUD)操作以及图像数据的存储和检索。 首先,Java与MongoDB的交互主要通过MongoDB的Java驱动程序实现...

    MongoDB 在java中的应用 纯Java操作

    ### MongoDB在Java中的应用 #### 一、MongoDB简介与安装步骤 MongoDB是一种非常流行的NoSQL数据库系统,尤其适用于需要处理非结构化或半结构化数据的应用场景。其灵活性和扩展性使得它成为众多开发者的首选。在...

    MongoDB on Kubernetes技术解决方案.pptx

    MongoDB on Kubernetes技术解决方案 MongoDB on Kubernetes技术解决方案旨在提供一种快速、灵活和高效的方式来部署和管理MongoDB数据库在Kubernetes集群中。该解决方案利用Kubernetes的强大API和Operator来实现...

    Mongodb常用命令和java调用

    MongoDB Java Driver提供了与MongoDB服务器通信的类和方法,使得Java应用能够无缝地与MongoDB集成。 总的来说,MongoDB的灵活性、强大的查询能力和高性能使其在处理复杂、非结构化或半结构化数据时表现出色。通过...

    mongodb_整合java_dao,以及用mongodb做附近人,或者是根据经纬多获取附近商家

    在Java开发中,我们通常使用MongoDB Java驱动程序来与数据库进行交互,实现DAO(Data Access Object)模式,以便更好地组织数据库操作。 在“mongodb_整合java_dao”这个主题中,我们将讨论如何在Java应用中集成...

    java 操作mongodb 增删改查

    在Java编程环境中,MongoDB是一个广泛使用的文档型数据库,它以JSON格式存储数据,提供了高性能、高可用性和可扩展性。本教程将详细介绍如何使用Java进行MongoDB的基本操作,包括增(添加数据)、删(删除数据)、改...

Global site tag (gtag.js) - Google Analytics