[记录]MongoDB Java代码---入门操作

MongoDB集群搭建与java代码操作MongoDB示例 MongoDB集群搭建与java代码操作MongoDB示例MongoDB集群搭建过程java使用MongoDB集群Demo MongoDB集群搭建过程 1. MongoDB Replica set集群搭建准备(主从仲裁) 介质(根据操作系统下载相应版本):https://www.mongodb.com/download-center/v2/community 集群配置手册(官方):https:/... 阅读详情
package com.gp;

import java.net.UnknownHostException;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

/**
 * 
 * @version 创建时间:2015年5月11日 下午4:01:48
 * @author 高攀
 *
 */
public class Test {
	
	public static void main(String[] args) throws UnknownHostException {
		
		// 建立MongoDB的链接
		Mongo db = new Mongo("127.0.0.1", 27017);
		// 获取当前链接到的服务器的数据库列表  
		List<String> list = db.getDatabaseNames();
		for (String string : list) {
			System.out.print(string+" ");
		}
		
		// 选择要操作的DataBsse
		DB dbb = db.getDB("mydb");
		// 选择collection
		DBCollection dbc = dbb.getCollection("mydb");
		
		
<span style="white-space:pre">	</span>        // a:存储数据到指定DB中
		BasicDBObject doc = new BasicDBObject();
		doc.put("name", "new1");
		doc.put("age", 22);
		doc.put("sex", "bunanbunv");
		//dbc.insert(doc); // 用于测试,注释了添加操作
		
		// 输出总记录数
		System.out.println(dbc.getCount());
		
		// 查询出所有结果
		DBCursor dbcur = dbc.find();
		/*while(dbcur.hasNext()){
			DBObject dbo = dbcur.next();
			System.out.print("name:"+dbo.get("name")+" age:"+dbo.get("age")+"\n");
		}*/
		
		// 把结果封装成JSON字符串
		JSONArray jsona = new JSONArray();
		jsona.add(dbcur.toArray());
		System.out.println(jsona);
		
		
	}
	
	
	

}

结果:

local mydb 33
[[{"sex":"nan","_id":{"new":false,"time":1431326465000,"inc":816505978,"timeSecond":1431326465,"machine":-726557157},"name":"gongpan1","age":21},{"sex":"nan","_id"}]]

JAVA 连接 mongoDB java连接mongoDB 1. 启动mongoDB认证 一、先启动mongoDB,进入mongoDB安装目录下bin文件夹中 ./mongod #启动mongo server服务,默认端口27017,默认允许本地连接 二、创建管理员用户 use admin #进入admin库 db.createUser({user:"test",pwd:"password",roles[ {role:"userAdminAnyDatabase","db":"admin" 阅读详情

相关推荐

手把手教你用C#和LibUsbDotNet实现USB设备通信(含完整代码示例)

本文详细介绍了如何使用C#和LibUsbDotNet库实现USB设备通信,包括设备识别、连接建立、同步/异步数据读写等核心操作。通过完整的代码示例,开发者可以快速掌握USB通信的关键技术,适用于工业自动化、医疗设备等多种场景。重点讲解了数据读写优化和错误处理技巧,帮助提升通信效率和可靠性。

a3b4c5的博客 705

net.sf.json.JSONObject cannot be cast to

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34185320的博客 8391

Ubuntu18.04 SoftRoCE安装教程

目标:创建两台Ubuntu18.04虚拟机,安装SoftRoCE环境,一台作为Server,一台作为Client,模拟RDMA通信环境,熟悉RDMA的通信方式。

GGGYL111的博客 1548

Java操作MongoDB之mongodb-driver

mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。 通过一个入门的案例来了解mongodb-driver的基本使用: 1、查询全部记录 1.1、创建工程mongoDemo,引入依赖 &amp;amp;amp;amp;amp;amp;lt;dependency&amp;amp;amp;amp;amp;amp;gt; &amp;amp;amp;amp;amp;amp;lt;groupId&amp;amp;amp;amp;a

脚印 3510

阿里云大模型ACP认证模拟考试(二)

摘要:在阿里云大模型高级工程师 ACP 认证暂无真题题库的现状下,模拟题具有重要意义。其依照真实考试设计,涵盖题型、题量与分值分布,助力考生熟悉考试框架,合理分配答题时间精力,提升效率。同时,模拟题紧扣官方课程,能帮助考生精准定位知识盲点,如大模型架构原理和通义千问应用实践等重点内容,以便针对性完善知识体系。此外,通过练习模拟题,考生可掌握不同题型的解题思维与技巧,快速洞察复杂题目本质,提高答题准确率。

davidkorhenn的博客 2074

零售-公司间关联交易退货STO的实现方式

零售-公司间关联交易采购 STO-退货 集团公司下经常会出现一家公司和另外一家公司的公司间的关联交易,如跨公司销售、总分公司之间采购,分公司之间的采购等业务;通常公司间采购会采取STO的模式来实现(根据业务模式可以将库存转储统一做成STO的模式,公司间STO、同公司工厂间、同工厂库存地点间 的STO SAP都是支持的); 公司间STO 正向A向B采购都很熟悉,公司间退货STO的其实也是比较普遍的业务现象,很多实施着也将其做成反向的STO(B向A采购),而不是退货STO(A向B,item 选择return的标

weixin_45518759的博客 2831

Java操作MongoDB

mongodb-driver mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。 我们通过一个入门的案例来了解mongodb-driver的基本使用 查询全部记录 创建工程 mongoDemo, 引入依赖 <dependencies> <dependency> <groupId>org.mongodb&lt...

L__MY的博客 264

【OpenCV-Python】——图像处理基础&读写及显示图像&读写及播放视频&灰度图/彩色图/图像通道操作、运算

在Python中,OpenCV使用NumPy数组存储图像,Numpy是使用Python进行数组计算的软件包,提供强大的N维数组对象,支持复杂的广播功能(数组运算),集成了C/C++和Fortran代码工具,支持线性代数、傅里叶变换和随机数等特性,还可作为通用数据的高效多维容器,如在OpenCV中显示图像。Numpy的知识点见数据处理专栏,主要包括数据类型、创建数组、数组形状、索引切片和迭代、数组运算等。作为初学者,里面可能有总结不全,后续深入学习后会改善文章!下次学习图形用户界面!

weixin_51658186的博客 2084

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

基于matlab不变矩的数字验证码识别系统

随着互联网技术的快速发展和应用,网络给人们提供了丰富的资源和极大的便利,但随之而来的是互联网系统的安全性问题,而验证码正是加强 Web 系统安全性的产物。全自动区分计算机和人类的图灵测试(Completely Automated Public Turing test to tell Computers and Humans Apart,CAPTCHA)也是验证码的一个应用程序,可以区分用户是人类还是计算机智能单击对象。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 917

2023年电工杯 | 2023年电工杯数学建模竞赛思路(A题、B题)

2023年电工杯 | 2023年电工杯数学建模竞赛思路(A题、B题)

前程算法屋的博客 5593

java操作mongodb获取记录数_Java操作MongoDB的常见API

package com.jadyer.test;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import org.bson.types.ObjectId;import org.junit.AfterClass;import org.junit.BeforeClass;im...

weixin_35041472的博客 941

小红书urlscheme和Activity

本文档详细介绍了小红书App的Deeplink跳转规范,涵盖了多个功能模块的跳转协议。主要内容包括:主页各Tab(关注、发现、购买)的跳转方式;不同类型笔记(图文/视频/长笔记)的详情页跳转参数;用户相关页面(主页/绑定/资料/消息等)的跳转协议;搜索功能(输入页/结果页)的跳转方式;以及话题、标签、专辑、H5页面等特殊场景的跳转实现。文档还提供了各跳转协议所需的参数说明,包括参数类型、默认值、是否必填等详细信息,并标注了不同版本和平台的兼容性要求。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 786

MongoDb Java操作MongoDB之Mongodb-Driver

操作Mongodb主要有两种 1:java MongoDB驱动程操作Mongogodb(相当于JDBC) 2:spring-data-mongodb 中的mongodbTemplate 这节附上java MongoDB驱动程操作Mongogodb的一些代码操作: pom文件如下: <!-- https://mvnrepository.com/artifact/org.mongodb/mong...

weixin_41987908的博客 1638

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

【MongoDB】常用操作记录

一、SpringBoot相关 1、模糊搜索 Criteria criteria = Criteria.where("字段1").regex(".*?" + query + ".*?"); 2、多个字段模糊搜索 Criteria criteria = new Criteria().orOperator( Criteria.where("字段1").regex(query), Criteria.where("字段2").r...

xmzmqx的博客 1899

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

MongoDB与JAVA CRUD

本文介绍java如何对MongoDB数据库进行CRUD

残缺的孤独 3018

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

腾讯Java开发面试凉凉,MongoDB入门操作汇总

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。**深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。

2401_83703951的博客 795

MongoDB入门手册

MongoDB是一个开源分布式的文档型NoSQL数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

白豆五的博客 1392

Java操作mongodb增删改查的基本操作

1、在项目中引入MongoDB驱动包2、创建类,执行以下步骤2.1.获取连接对象:【MongoClient mc = new MongoClient("localhost",27017);】2.2.获取并创建库对象:【MongoDatabase db = mc.getDatabase("myschool");】

qq_52025132的博客 3572

mongodb java查询_java操作mongoDB查询的实例详解

java操作mongo查询的实例详解前言:MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强...

weixin_42601608的博客 3368

文档型数据库MongoDB-Java操作MongoDB

文档型数据库MongoDB-Java操作MongoDBmongodb-driver查询全部记录条件查询(1)查询userid为1013的记录(2)查询浏览量大于1000的记录插入数据SpringDataMongoDB mongodb-driver mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们通过一个入门的案例来了解mongodb-d...

shenzhen_zsw的专栏 487

java 操作 mongodb_Java操作MongoDB数据库方法详解

Java与mongodb的连接1. 连单台mongodbMongo mg = new Mongo();//默认连本机127.0.0.1 端口为27017Mongo mg = new Mongo(ip);//可以指定ip 端口默认为27017Mongo mg = new Mongo(ip,port);//也可以指定ip及端口2. 连双台mongodb//ip为主机ip地址,port为端口号,data...

weixin_39928736的博客 1868

mongodb 操作记录

mongodb 操作记录

野路子云遇见不同的自己 671

学习MongoDB,在java中使用MongoTemplate聚合操作MongoDB

1.聚合操作Aggregation介绍    Aggregation简单来说,就是提供数据统计、分析、分类的方法,这与mapreduce有异曲同工之处,只不过mongodb做了更多的封装与优化,让数据操作更加便捷和易用。Aggregation操作,接收指定collection的数据集,通过计算后返回result数据;一个aggregation操作,从input源数据到output结果数据,中间会...

街角有人祝福,巷口有人哭~ 1万+
上一篇: [分享]关于异常里面的finally代码块执行时机
下一篇: [分享]Java之Bean、Map、Json之间的互相转换工具类
51码上有猿
博客等级 码龄14年 321粉丝 69原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值