JAVA操作MongoDB

解决mongodb连接的失败的问题 解决mongodb连接的失败的问题 Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='root', source='iot', password=, mechanismProperties={}}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{me 阅读详情


1、驱动下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/


2、MongoDB API Docs for java

    http://api.mongodb.org/java/index.html

3、Getting started with Java

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 onlineAPI Documentation for Java Driver.

A Quick Tour

Using the Java driver is very simple. First, be sure to include thedriver jar mongo.jar in your classpath. The following codesnippets come from the examples/QuickTour.java example codefound in the driver.

Making a Connection

To make a connection to a MongoDB, you need to have at the minimum, thename 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 whenconnecting. The following example shows three ways to connect to thedatabase 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;

// To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
// if it's a member of a replica set:
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, 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 = mongoClient.getDB( "mydb" );

At this point, the db object will be a connection to a MongoDB serverfor the specified database. With it, you can do further operations.

Note

The MongoClient instance actually represents a pool ofconnections to the database; you will only need one instance ofclass MongoClient even with multiple threads. See theconcurrency doc page for moreinformation.

The MongoClient class is designed to be thread safe and sharedamong threads. Typically you create only 1 instance for a givendatabase cluster and use it across your application. If for some reasonyou decide to create many MongoClient instances, note that:

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

New in version 2.10.0: The MongoClient class is new in version 2.10.0. For releasesprior to that, please use the Mongo class instead.

Authentication (Optional)

MongoDB can be run in a secure mode where access to databases iscontrolled through name and password authentication. When run in thismode, any client application must provide a name and password beforedoing any operations. In the Java driver, you simply do the followingwith 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 betrue. Otherwise, it will be false. You should look at theMongoDB 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 ofthem 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 tothe getCollection(String collectionName) method:

DBCollection coll = db.getCollection("testCollection");

Once you have this collection object, you can now do things like insertdata, query for data, etc

Setting Write Concern

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

mongoClient.setWriteConcern(WriteConcern.JOURNALED);

There are many options for write concern. Additionally, the defaultwrite concern can be overridden on the database, collection, andindividual update operations. Please consult the API Documentation fordetails.

Changed in version 2.10.0: Prior to version 2.10.0, the default write concern isWriteConcern.NORMAL. Under normal circumstances, clients willtypically change this to ensure they are notified of problemswriting to the database.

Inserting a Document

Once you have the collection object, you can insert documents into thecollection. For example, lets make a little document that in JSON wouldbe 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 dothis, we can use the BasicDBObject class to create the document(including the inner document), and then just simply insert it into thecollection 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, wecan do a simple findOne() operation to get the first document in thecollection. This method returns a single document (rather than theDBCursor that the find() operation returns), and it’s useful for thingswhere there only is one document, or you are only interested in thefirst. 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 yourdocument. 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 multiplesimple 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 samecollection. 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, plusthe 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 thefind() method. The find() method returns a DBCursor object which allowsus to iterate over the set of documents that matched our query. So toquery 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 ofthe documents in our collection. For example, if we wanted to find thedocument for which the value of the “i” field is 71, we would do thefollowing ;

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

Quick Tour of the Administrative Functions

Creating An Index

MongoDB supports indexes, and they are very easy to add on acollection. To create an index, you just specify the field that shouldbe indexed, and specify if you want the index to be ascending (1)or descending (-1). The following creates an ascending index on thei 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} }

Getting A List of Databases

You can get a list of the available databases:

MongoClient mongoClient = new MongoClient();

for (String s : mongoClient.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");

4、Release Notes

    https://github.com/mongodb/mongo-java-driver/wiki/Release-Notes

Arduino粉尘传感器DIY:打造智能PM2.5监测仪 本文详细介绍了如何利用Arduino和粉尘传感器DIY一个智能PM2.5监测仪。从硬件选购、接线步骤到代码编写,提供了完整的制作指南,帮助读者以低成本打造透明可靠的空气质量监测设备,并探讨了数据解读与智能升级方案。 阅读详情

相关推荐

【GPT】Coze使用开放平台接口-【7】Dify 比较篇

coze 用于社交,dify 用来内部构建。抛开工作流,机器人,工具,coze 最大的区别在于可以直接发布到社交媒体上。所以,coze 对操作体验上也花了不少功夫,而 dify 就专注在帮助使用者打磨工作流。coze 各个大模块之前可以联动的机制也比较多,所以侧重点各不相同。

非晓为骁的博客 7613

MongoDB -- MongoClient连接池用法

主要的调整在于2.10.0版本中引入了MongoClient类,同时在其API中也说明了Mongo类会在将来的版本中被MongoClient替换(Note: This class has been superseded by MongoClient, and may be deprecated in a future release.)。故在这次调整中,也对原先的Mongodb部分做了相应的修改。M

GP的空间 5万+

从零开始,手把手教你用RTL代码设计一个简单的8位CPU(附状态图与ALU设计)

本文详细介绍了如何从零开始设计一个简单的8位CPU,包括状态机设计、ALU实现与RTL编码实战。通过具体的指令集分析、状态图设计和Verilog代码示例,帮助读者深入理解CPU工作原理,并掌握RTL代码编写技巧。特别适合计算机系统学习者和硬件设计爱好者。

weixin_30847063的博客 320

解决An error occurred while creating the AVD. See idea.log for details问题

第一种解决办法:先卸载Android Emulator然后再次安装,我尝试了,但是没解决。最后我参考如下文章修改环境变量,更改了AVD的默认路径,成功解决。

Asitisl的博客 6601

调用IP核、移植/复制IP核以及解决IP核被锁住/红锁问题(基于vivado)

解决不同工程IP核之间复制调用以及IP核红锁问题,让开发更简单!

weixin_44502554的博客 1万+

经典EMC案例-汽车车载电子行车记录仪显示屏EMC BCI整改案例

拿到这款汽车前装车载电子行车记录仪,小编首先在实验室还原客户描述的现象,确定现象符合客户的描述,再根据现象出现的对应频率做好记录,因为通常BCI FAIL的现象不局现于一个频率点,然后通过这些现象及频点,再结合产品的构造、线束,分析构思出大致解决方案。

jack_luo4913的博客 3738

An unexpected error occurred: “: getaddrinfo ENO

getaddrinfo ENO An unexpected error occurred: "https://raw.githubusercontent.com/eligrey/FileSaver.js/e865e37af9f9947ddcced76b549e27dc45c1cb2e/package.json: getaddrinfo ENO 解决方法 打开浏览器,访问https://www.ipaddress.com,查一下raw.githubusercontent.com 的ipv4地址...

hlqiong的博客 1031

逆向某团mtgsig参数时,我踩过的3个坑:从H5guard混淆到Python校验

本文详细解析了逆向某团mtgsig参数时遇到的三大挑战:H5guard混淆破解、环境补全检测与Python结果校验。通过实战案例,揭示了JavaScript加密算法的逆向技巧,包括控制流混淆拆解、隐蔽环境检测点规避以及跨语言校验的解决方案,为开发者提供了一套完整的逆向工程避坑指南。

weixin_27722377的博客 1061

使用Java API 操作MongoDB

本次每个操作都创建了一个.java文件,如下所示(不包含Java_mongodb.java和Main.java):遇到的问题:IDEA输出结果乱码!idea乱码解决方式大汇总_idea 乱码-优快云博客。

xuhuishao的博客 3642

树莓派4B系统安装及SSH远程控制(简单易操作)

​自从2022年4月树莓派官网更新了RaspberryPiImager版本v1.7.2后,便不再支持自行建立ssh文件,并用默认用户名pi和密码raspberry的方式进行远程控制(亲测不行,输密码时一直access denied)。但是该版本软件提供了烧录系统前设置ssh用户及密码功能。本文记录了系统安装和SSH远程操作步骤。........................

机械人的代码路 5790

超详细流式细胞术全流程解析:从样本制备到结果分析全攻略

流式细胞术(Flow Cytometry)是现代生物学和医学研究中不可或缺的高通量分析技术,可实现对细胞表型、功能状态、细胞周期等多维度参数的快速检测。本文将从实验全流程出发,详解样本制备、上机操作、参数设置及结果处理的核心要点,帮助科研人员精准掌握流式实验关键技术。

good_rrrrr的博客 3868

使用Java操作mongoDB

使用Java操作mongoDB,对mongoDB进行增删改查等操作

wr456wr的博客 2890

网表导入virtuoso后发现pg pin忘记connect_pg_net/globalNetConnect怎么办?

数模混合项目中经常需要一些需要到virtuoso去连接的线,比如IO上的pg和一些信号线,除了在pr工作中设置skip route之外还需要做好net的赋值,告诉工具虽然我没在物理上有连接,但是实际上应该连什么net,这部分提现在网表里。在Default Net Name中也填写net name,因为这个net需要做global操作,即在顶层定义这个net,所以需要在net name后加个!打开schematic,删除指定cell pin所接net的label。

m0_61544122的博客 969

【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.youkuaiyun.com/IBM_hoojo http://hoojo.cnblogs.com/ ...

编程知识分享 327

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

java 操作mongodb_Java操作MongoDB

之前我们介绍的MongoDB的操作都是在shell命令中写的,在项目开发时我们当然都是用程序去操作MongoDB的,本文我们来看看如何用Java代码操作MongoDB。本文是MongoDB系列的第十九篇文章,了解前面的文章有助于更好的理解本文:准备工作首先我们需要驱动,MongoDB的Java驱动我们可以直接在Maven中央仓库去下载,也可以创建Maven工程添加如下依赖:org.mongodbm...

weixin_26900991的博客 392

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Java操作MongoDB

Java操作MongoDB 个人分类: Java技术 MongoDB 数据库 本篇博客学习如何用Java操作MongoDB,希望能给各位博友带来帮助。 Java操作MongoDB mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们通过一个入门的案例来了解mongodb-driver的基本使用。 (1)创建工程 mongoDemo, 引入依...

DLLLL_的博客 271

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java操作mongodb_Java操作MongoDB

一、准备工作1、 首先,下载mongoDB对Java支持的驱动包2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用mongoDB,目录如下:二、Java操作MongoDB示例在本示例之前你需要启动mongod.exe的服务,启动后,下面的程序才能顺利执行;1、 建立SimpleTest.java,完成简单的mongoDB数据库操作Mongo mongo = n...

weixin_30698949的博客 1195

MongoDB(三) - 掌握 Java 操作 MongoDB,看这一篇就够了

在现代软件开发中,数据库操作是至关重要的一环。MongoDB 作为一款流行的 NoSQL 数据库,以其灵活的数据模型、高扩展性和出色的性能,被广泛应用于各类项目中。本文将详细介绍如何在 Java 项目中使用 MongoDB,从项目创建、依赖导入,到数据库、集合、文档的各种操作,以及聚合查询等高级应用,帮助读者快速掌握在 Java 环境下操作 MongoDB 的技能。

zcs2312852665的博客 2208

Mongodb Java操作

最近终于感觉到了java的一个最好的特点:跨平台。 终于不用管移植的问题了。 去mongodb官网上下载java的开发包 添加进安装java时设置的class path中(系统环境变量里面) 就可以操作了。 给出一段代码: //package com.mkyong.core; import java.net.UnknownHostException; import com.mongod

Json_Nie的专栏 806

java 操作 mongodb

HelloWorld程序   学习任何程序的第一步,都是编写HelloWorld程序,我们也不例外,看下如何通过Java编写一个HelloWorld的程序。   首先,要通过Java操作Mongodb,必须先下载Mongodb的Java驱动程序,可以在这里下载。   新建立一个Java工程,将下载的驱动程序放在库文件路径下,程序代码如下: package com.mkyon

tango991820的专栏 3078

MongoDB for Java】Java操作MongoDB

http://www.cnblogs.com/sourire/archive/2010/07/07/1772798.html http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html MongoDB 安装与启动 主要介绍在Windows 与 Linux 下的安装与启动 下载链接:http://www.mongod

woshizoe的专栏 460

java 操作Mongodb

实际的联查写法。

weixin_43102784的博客 1750

【Java使用mongodb-driver来操作mongodb】

Java使用mongodb-driver来操作mongodb 创建新工程 创建新的demo工程,引入MongoDB的jar包的坐标: <dependencies> <!--mongo依赖--> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifact

Mrchai521的博客 920
上一篇: Java分布式事务
下一篇: SOLR的一些错误
LiHangTong
博客等级 码龄16年 11粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值