Mongodb java tutorial

[size=medium]
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();
// or
Mongo m = new Mongo( "localhost" );
// or
Mongo m = new Mongo( "localhost" , 27017 );
// or, to connect to a replica set, supply a seed list of members
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

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

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

{
"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 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)); // 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();

query.put("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:

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");[/size]
simulink的电动汽车制动系统热管理仿真 本文系统研究了电动汽车制动系统热管理仿真技术。通过建立机电液多物理场耦合模型,分析了不同工况下的动态热平衡特性。提出基于MPC的动态调节和NSGA-II多目标优化算法,使电池温度波动降低60%。创新性采用石墨烯相变材料与微通道液冷复合技术,冷却系统能耗减少40%。研究构建了完整的工程验证平台,涵盖200kW电制动测试台和高精度热成像系统。展望指出,未来将结合Transformer预测和强化学习算法,进一步优化热管理策略。该研究为电动汽车制动系统热管理提供了从理论建模到工程实施的完整解决方案。 阅读详情

相关推荐

RJ45以太网接口EMC设计方案

RJ45以太网接口EMC设计方案 一、 接口概述 RJ45以太网接口是目前应用最广泛的通讯设备接口,以太网口的电磁兼容性能关系到通讯设备的稳定运行。赛盛技术应用电磁兼容设计平台(EDP)软件从接口原理图、结构设计,线缆设计三个方面来设计以太网口的EMC设计方案。 二、 接口电路 原理图的EMC设计 百兆以太网接口2KV防雷滤波设计 图1 百兆以太网接口2KV防雷滤波设计 接口电路设计概述: 本方案从EMC原理上,进行了相关的抑制干扰和抗敏感度的设计;从设计层次解决EMC问题;同时此电路兼容了百兆以太网接

兰陵笑笑生SD的博客 1万+

[翻译官方文档]Java Tutorial(Java操作MongoDB入门)

为什么80%的码农都做不了架构师?>>> ...

weixin_34198583的博客 230

FPGA工程师必看:JESD204B同步机制实战指南(含SYSREF信号调试技巧)

本文为FPGA工程师提供了一份JESD204B同步机制的实战指南,重点聚焦于SYSREF信号的调试技巧。文章从同步的核心逻辑出发,深入剖析了时钟、SYSREF与对齐序列这“三驾马车”的协作,并详细阐述了硬件PCB布局、FPGA IP核配置、状态机监控以及使用示波器进行波形分析等关键实战步骤,旨在帮助工程师解决多通道高速系统中的同步难题,确保链路的稳定与确定性延迟。

weixin_29239661的博客 333

Java tutorial - collections

Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, andProperties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a ce

michelyang1990的专栏 480

Keil环境下单片机串口通信实战:如何用printf发送中文(附完整代码)

本文详细解析了在Keil开发环境下,单片机通过串口通信发送中文信息时产生乱码的根本原因及解决方案。核心在于理解并统一编码(如GB2312或UTF-8),并正确重定向printf函数。文章提供了针对STC89C52和STM32F103的完整代码示例,涵盖工程配置、编码设置、调试技巧,帮助开发者实现稳定可靠的中文串口输出。

weixin_29168675的博客 468

System Verilog学习笔记(十九)——覆盖率

覆盖率是用来衡量验证精度和完备性的数据指标。也可以告诉我们在仿真时设计的哪些结构被触发,哪些没被触发。高质量的验证需要满足以下三个条件。

ljy77882333的博客 2144

Python-MongoDB官方文档翻译

文章首发:点点寒彬的博客前言都说MongoDB这个NoSql数据库特别友好,使用起来也非常方便,今天稍微接触了一下,发现真的是非常非常简单,但是网上对这块内容涉及的很少,而且很多内容都是很老的版本使用的方法,我看了一下官方API文档中描述的内容也不多,顺手翻译一下吧,造福一下后来人。注:我并不是逐字逐句的翻译,在某些地方我无法精确翻译的时候,我概括了大概的意思,有能力的可以直接看官方文档前提条件首先

点点寒彬的博客 1459

手把手教你用Python 3.11和Node.js 18在Windows 11上搭建Dify开发环境

本文提供了一份详尽的Windows 11本地Dify开发环境搭建指南。文章手把手教你完成从Python 3.11、Node.js 18的安装配置,到PostgreSQL、Redis数据库服务的部署,再到前后端服务的启动与联调的全过程,并包含常见问题排查与效能优化建议,旨在帮助开发者构建一个稳定、可调试的Dify本地开发环境。

fire9的博客 645

JavaBeginnersTutorial 中文系列教程·翻译完成

原文:JavaBeginnersTutorial 协议:CC BY-NC-SA 4.0 欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远。 在线阅读 ApacheCN 学习资源 目录 JavaBeginnersTutorial 中文系列教程 Java 教程 Java 教程 – 入门 Java 的历史 Java 基础知识:Java 入门 jdk vs jre vs jvm public static void main(string args[])说明 面向初学者的 Java 类.

龙哥盟 3万+

Habitat-v0.1.7安装全网最详细教程(解决habitat-sim下载时网络问题)

Habitat-v0.1.7安装全网最详细教程(解决habitat-sim下载时网络问题)

shannanshouyin的博客 1328

AUTOSAR知识点 之 XCP (三):XCP功能描述

记录一下XCP使用时候的功能包含命令时序、错误码表、事件描述以及对规范的记录。XCP的图示如下从上图就可以看出数据流的流向CAN-CANIF-XCP,发送反之。XCP的状态机如下。

梦想技术家 3079

Java Fundamentals Tutorial: Java Collections and Generics

Java Fundamentals Tutorial: Java Collections and Generics原网址:https://newcircle.com/bookshelf/java_fundamentals_tutorial/generics_collections13.Java Collections and GenericsThe Java Collect...

weixin_33721344的博客 304

最新2026年《网络数据安全风险评估办法》条款解读

大型企业集团IT变革下的零信任安全体系建设方案(55页).pptx。以数据安全为核心的安全立体防御体系解决方案(41页).pptx。让数据安全合规地创造价值(15页 PPT).pptx。大型集团数据安全应急预案(57页).docx。数据安全治理与评估服务业务介绍.pptx。数据安全管理实践(17页).pptx。大数据安全架构设计方案.pptx。大数据安全规划总体方案.pptx。数据库安全综合治理方案.pptx。医疗数据安全建设方案.pptx。数据安全框架规划图.pptx。数据安全治理方案.pptx。

cdfunlove的博客 47

MongoDB 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 Qui

yuwenruli的专栏 1659

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Java-MongoDB Tutorial

从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 J...

学无止境 196

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Java MongoDB Tutorial

The following Java / Spring Data MongoDB tutorials and examples are tested with : MongoDB 2.2.3 Java-MongoDB-Driver 2.11.0 Spring-Data-MongoDB 1.2.0.RELEASE 1. MongoDB Core Examples MongoDB in...

iteye_5347的博客 138

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Java Tutorial(Java操作MongoDB入门)

插入代码太麻烦了,凑合看吧。 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 Docum

Noday 3094

java mongodb开发_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 ...

weixin_32296949的博客 174

java操作mongodb文档_【Java操作】[翻译官方文档]Java Tutorial(Java操作MongoDB入门)...

(Java操作MongoDB入门)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 Doc...

weixin_29421255的博客 305

Spring Data MongoDB –聚合分组示例

在本教程中,我们将向您展示如何使用Spring Data + MongoDB聚合框架进行数据分组。 1.测试数据 domain.json { "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" } { "_id" : 2, "domainName" : "test2.com", "hosting" : ...

一名可爱的技术搬运工 754

Java MongoDB:插入文档

在本教程中,我们向您展示了通过Java MongoDB API在JSON数据下方插入“ 文档 ”的4种方法。 测试数据 以JSON格式测试数据。 { "database" : "mkyongDB", "table" : "hosting", "detail" : { records : 99, index : "vps_index1", active :...

一名可爱的技术搬运工 453

Java实现对MongoDB的AND、OR和IN操作

很全的JAVA操作mongodb: http://www.blogjava.net/xiaomage234/archive/2012/08/06/384904.html   转的:   AND: public void testAnd(){ //agender='female' AND age > 27 DBObject queryCondition = n

石头视角 3233

MongoDB 3.0 速上手教程(JAVA)

最近做项目想用一下NoSQL数据库,由于项目需要保存大量的json数据,我就选了MongoDB作为我的数据库。 最新版为3.0 下载安装都很容易,今天按照教程一步一步实现了增删改查等工作,本文将把要用到的代码都贴上来而且都做好中文注释方便大家阅读。 过程中发现两处不能使用教程中的代码实现的地方,经过查资料已经用另外的方法实现了,不知道是不是叫承重的代码出错了还是什么原因,如果有知道的朋友请...

jcs130的专栏 349

mongodb+java实现日志的日活与月活查询

业务介绍前段时间有个日志统计的需求,是规范的登陆日志,估计一个月有几十万,放入hadoop太麻烦了,放数据库又怕后续数据量增加较快,于是尝试用mongodb来存储,后续进行统计。 mongodb是采用3.4, 2017年12月最新的是3.6

mingover的专栏 3332

MongoDB在Linux上搭建和简单使用

环境:CentOS7,Mongo:mongodb-linux-x86_64-amazon-3.2.11.tgz Mongo下载:https://www.mongodb.com/download-center?jmp=nav#community 1. 解压:tar -zxvf mongodb...

chuangfuli5617的博客 219
上一篇: Java Thread 多线程理论 目录索引
下一篇: 查找最大子数组
mainmonkey
博客等级 码龄14年 1粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值