热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Java操作MongoDB入门

插入代码太麻烦了,凑合看吧。Introduction介绍ThispageisabriefoverviewofworkingwiththeMongoDBJavaDriver.这是使用MongoDBjava驱动的简单说明。FormoreinformationabouttheJavaAPI,pleaserefertotheo
插入代码太麻烦了,凑合看吧。 

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()关闭资源
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 :
MongoDB可以运行在通过用户名和密码控制的安全的模式下。当以安全模式运行时,任何客户端应用程序的操作必须验证用户名和密码。在java中,验证很简单:

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.
如果用户名和密码正确,auth值为true。错误为false。在日志中可以看到更多有效的信息。
Most users run MongoDB without authentication in a trusted environment.
很多用户将MongoDB以非授权模式运行在安全的环境中。
Getting A List Of Collections
查询Collection的集合(Collection类似于表)
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
每个数据库可以有任意个collection。通过db对象可以检索并打印出来:
Set 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两个collection,结果输出入下
name
address

as the output.

Getting A Collection
得到Collection
To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
要使用collection,使用getCollection(String collectionName) 方法传入collection的名称:
DBCollection coll = db.getCollection("testCollection")

Once you have this collection object, you can now do things like insert data, query for data, etc
得到collection对象后就可以进行插入、查询等操作了。
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
得到collection对象就可以把documents插入到collection中。例如,创建一个如下的JSON文档
{
   "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.
注意,上面的文档中有个内部文档(就是{ x : 203, y : 102})。存储上面的文档,可以使用BasicDBObject 类来创建文档(包括inner文档),使用insert()方法可以简单的把文档插入collection中。
        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()
使用findOne()方法查找collection中的第一个文档document
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.
可以使用findOne()操作来查找collection中的第一个文档来显示上一步中插入的文档。方法返回一个文档,用来找只有一个文档或第一条文档很实用。可以不使用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.
注意,_id元素是MongoDB自动添加的。MongoDB内部的元素以"_"/"$"开始。
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"
注意,可以在一个collection中插入不同类型的文档。就是说MongoDB是"schema-free"(什么意思?)
Counting Documents in A Collection
统计collection中所有的document数量
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.
现在,插入了101个文档(循环的100个和第一个),使用getCount()检查一下。
System.out.println(coll.getCount());

and it should print 101.
输出结果是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 :
使用find()来查找所有的document。find()方法查询返回一个可以遍历文档集合的DBCursor 对象。如下:
        DBCursor cur = coll.find();

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

and that should print all 101 documents in the collection.
打印所有的document
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 ;
可以通过find()方法查找部分document,例如,如果想查找i=71的document,这样做
        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
会打印找到的单个document
{ "_id" : "49903677516250c1008d624e" , "i" : 71 }

You may commonly see examples and documentation in MongoDB which use $ Operators, such as this:
MongoDB文档和例子中经常出现$操作符,如下
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));

        cur = coll.find(query);

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


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 :
例如,想找"i">50的文档,这样做:
        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>50的文档。也可以查找范围如20         query = new BasicDBObject();

        query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));  // i.e.   20

        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 :
MongoDB支持索引,并且很容易添加。只需要指定索引的字段和排序(升序1,降序-1)。下面是创建i降序索引的例子:
        coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

Getting a List of Indexes on a Collection
查询collection全部索引
You can get a list of the indexes on a collection :

        List 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");
 Loading...

--------------------------------------------------------------------------------

Added by Rian Murphy, last edited by Scott Hernandez on May 05, 2011
翻译:Noday(noday.net)于20110629晚 (没过4级的家伙,全凭感觉翻译,欢迎讨论指正)


推荐阅读
  • Allegro总结:1.防焊层(SolderMask):又称绿油层,PCB非布线层,用于制成丝网印板,将不需要焊接的地方涂上防焊剂.在防焊层上预留的焊盘大小要比实际的焊盘大一些,其差值一般 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • Linux如何安装Mongodb的详细步骤和注意事项
    本文介绍了Linux如何安装Mongodb的详细步骤和注意事项,同时介绍了Mongodb的特点和优势。Mongodb是一个开源的数据库,适用于各种规模的企业和各类应用程序。它具有灵活的数据模式和高性能的数据读写操作,能够提高企业的敏捷性和可扩展性。文章还提供了Mongodb的下载安装包地址。 ... [详细]
  • 恶意软件分析的最佳编程语言及其应用
    本文介绍了学习恶意软件分析和逆向工程领域时最适合的编程语言,并重点讨论了Python的优点。Python是一种解释型、多用途的语言,具有可读性高、可快速开发、易于学习的特点。作者分享了在本地恶意软件分析中使用Python的经验,包括快速复制恶意软件组件以更好地理解其工作。此外,作者还提到了Python的跨平台优势,使得在不同操作系统上运行代码变得更加方便。 ... [详细]
  • 【技术分享】一个 ELF 蠕虫分析
    【技术分享】一个 ELF 蠕虫分析 ... [详细]
  • Abp+MongoDb改造默认的审计日志存储位置
    一、背景在实际项目的开发当中,使用AbpZero自带的审计日志功能写入效率比较低。其次审计日志数据量中后期十分庞大,不适合与业务数据存放在一起。所以我们可以重新实现A ... [详细]
  • C++程序员视角下的Rust语言
    自上世纪80年代初问世以来,C就是一门非常重要的系统级编程语言。到目前为止,仍然在很多注重性能、实时性、偏硬件等领域发挥着重要的作用。C和C一样&#x ... [详细]
  •     系统采用jeeplus框架(ssm+redis+shiro+mongodb+redis),默认是做了JSP未做前后端分离,由于业务需要已经多终端使用的需求(H5、小程序等) ... [详细]
  • mongoDB高可用集群环境搭建
    2019独角兽企业重金招聘Python工程师标准在生产环境下,部署一台mongodb服务的话,会存在以下问题:单点问题生产环境是一个 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
  • 本文详细介绍了云服务器API接口的概念和作用,以及如何使用API接口管理云上资源和开发应用程序。通过创建实例API、调整实例配置API、关闭实例API和退还实例API等功能,可以实现云服务器的创建、配置修改和销毁等操作。对于想要学习云服务器API接口的人来说,本文提供了详细的入门指南和使用方法。如果想进一步了解相关知识或阅读更多相关文章,请关注编程笔记行业资讯频道。 ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
author-avatar
振芳婉仁正君
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有