Java中连接Mongodb进行操作

news2024/9/20 5:54:37

文章目录

  • 1.引入Java驱动依赖
  • 2.快速开始
    • 2.1 先在monsh连接建立collection
    • 2.2 java中快速开始
    • 2.3 Insert a Document
    • 2.4 Update a Document
    • 2.5 Find a Document
    • 2.6 Delete a Document

1.引入Java驱动依赖

注意:启动服务的时候需要加ip绑定
需要引入依赖

<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>5.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/bson -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>bson</artifactId>
      <version>5.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-core -->
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-core</artifactId>
      <version>5.1.0</version>
    </dependency>

2.快速开始

2.1 先在monsh连接建立collection

db.players.insertOne({name:"palyer1",height:181,weigh:90})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e0a522ef6dba6a26a13')
}
test> db.players.insertOne({name:"palyer2",height:190,weigh:100})
{
  acknowledged: true,
  insertedId: ObjectId('665c5e18522ef6dba6a26a14')
}
test> db.players.find()
[
  {
    _id: ObjectId('665c5e0a522ef6dba6a26a13'),
    name: 'player1',
    height: 181,
    weigh: 90
  },
  {
    _id: ObjectId('665c5e18522ef6dba6a26a14'),
    name: 'player2',
    height: 190,
    weigh: 100
  }
]

2.2 java中快速开始

public class QuickStart {

    public static void main(String[] args) {
        // 连接的url
        String uri = "mongodb://node02:27017";
        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("test");
            MongoCollection<Document> collection = database.getCollection("players");
            Document doc = collection.find(eq("name", "palyer2")).first();
            if (doc != null) {
                //{"_id": {"$oid": "665c5e18522ef6dba6a26a14"}, "name": "palyer2", "height": 190, "weigh": 100}
                System.out.println(doc.toJson());
            } else {
                System.out.println("No matching documents found.");
            }
        }
    }

}

2.3 Insert a Document

 @Test
    public void InsertDocument()
    {
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        try {
            // 插入地图文档
            InsertOneResult result = collection.insertOne(new Document()
                    .append("_id", new ObjectId())
                    .append("name", "beijing")
                    .append("longitude", "40°N")
                    .append("latitude", "116°E"));
            //打印文档的id
            //Success! Inserted document id: BsonObjectId{value=665c6424a080bb466d32e645}
            System.out.println("Success! Inserted document id: " + result.getInsertedId());
            // Prints a message if any exceptions occur during the operation
        } catch (MongoException me) {
            System.err.println("Unable to insert due to an error: " + me);
        }

2.4 Update a Document

 @Test
    public void UpdateDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        //构造更新条件
        Document query = new Document().append("name",  "beijing");
        // 指定更新的字段
        Bson updates = Updates.combine(
                Updates.set("longitude", "40.0N"),
                Updates.set("latitude", "116.0E")
        );
        // Instructs the driver to insert a new document if none match the query
        UpdateOptions options = new UpdateOptions().upsert(true);
        try {
            // 更新文档
            UpdateResult result = collection.updateOne(query, updates, options);
            // Prints the number of updated documents and the upserted document ID, if an upsert was performed
            System.out.println("Modified document count: " + result.getModifiedCount());
            System.out.println("Upserted id: " + result.getUpsertedId());

        } catch (MongoException me) {
            System.err.println("Unable to update due to an error: " + me);
        }
    }

2.5 Find a Document

 @Test
    public void testFindDocuments(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        // 创建检索条件
        /*Bson projectionFields = Projections.fields(
                Projections.include("name", "shanghai"),
                Projections.excludeId());*/
        // 匹配过滤检索文档
        MongoCursor<Document> cursor = collection.find(eq("name", "shanghai"))
                //.projection(projectionFields)
                .sort(Sorts.descending("longitude")).iterator();
        // 打印检索到的文档
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }

检索

2.6 Delete a Document

 @Test
    public void DeleteDocument(){
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("map");
        Bson query = eq("name", "shanghai");
        try {
            // 删除名字为shanghai的地图
            DeleteResult result = collection.deleteOne(query);
            System.out.println("Deleted document count: " + result.getDeletedCount());
            // 打印异常消息
        } catch (MongoException me) {
            System.err.println("Unable to delete due to an error: " + me);
        }
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1794310.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Qt无边框

最简单的可拖动对话框(大小不可改变) #ifndef DIALOG_H #define DIALOG_H/*** file dialog.h* author lpl* brief 无边框dialog类* date 2024/06/05*/ #include <QDialog> #include <QMouseEvent> namespace Ui { class Dialog; } /*** brief The Dialog class* 无…

Shopee本土店成本利润如何核算?EasyBoss ERP帮您精准掌控

这几年做跨境电商的老板们都在说东南亚市场广阔&#xff0c;在东南亚开本土店流量大&#xff0c;为了赚钱兴冲冲跑去东南亚开本土店&#xff0c;每天看着店铺不停出单。 心里乐呵呵&#xff1a;“本土店是真赚钱&#xff0c;马上要走上人生巅峰了&#xff01;” 但每月实际一对…

PbootCms微信小程序官网模版/企业官网/社交电商官网/网络工作室/软件公司官网

在数字化时代&#xff0c;企业网站已成为吸引潜在客户、提升企业形象、和扩大品牌影响力的必备工具。因此&#xff0c;一个优秀的企业网站模板显得尤为重要。 企业官网的内容框架通常都包含企业形象、产品或服务类型、信息展示等部分&#xff0c;设计师需要借助和企业形象契合…

图片改大小的3个步骤,快速在线处理图片的方法

图片改大小是现在使用图片时经常要使用的一个功能&#xff0c;因为在很多的网上平台都会有对图片尺寸和图片大小的要求&#xff0c;只有符合平台要求的图片才可以正常上传使用。想要快速调整图片大小&#xff0c;可以在网上使用在线改图工具来处理&#xff0c;只需要简单的几步…

快速上手 ngrok:将你的本地服务一键暴露到互联网,开发者必备技能!

想让外界轻松访问你本地电脑上的项目&#xff1f;试试 ngrok 吧&#xff01;无论是调试 Web 应用&#xff0c;还是进行跨网络测试&#xff0c;ngrok 都能帮你一键创建安全隧道&#xff0c;将本地服务映射到公共 URL&#xff0c;让全球任何地方都能访问。本文详细介绍 ngrok 的安…

2.1.3 采用接口方式使用MyBatis

实战概述&#xff1a;使用MyBatis的接口方式进行数据库操作 环境准备 确保项目中已经集成了MyBatis框架。 创建用户映射器接口 在net.huawei.mybatis.mapper包中创建UserMapper接口。定义方法findById(int id)用于按编号查询用户。定义方法findAll()用于查询全部用户。定义方法…

Python 识别图片形式pdf的尝试(未解决)

想识别出pdf页面右下角某处的编号。pdf是图片形式页面。查了下方法&#xff0c;有源码是先将页面提取成jpg&#xff0c;再用pytesseract提取图片文件中的内容。 直接用图片来识别。纯数字的图片&#xff0c;如条形码&#xff0c;可识别。带中文的不可以&#xff0c;很乱。 识别…

jupyter之plt 画图弹出窗口展示图片以及静态图片切换方法

1. jupyter出图的三种方式 在python的Jupyter Notebook中&#xff0c;使用matplotlib绘制动态图形时&#xff0c;可能出现只显示一张静态图像。 这是因为在notebook中使用plt绘图共有三种模式&#xff1a; %matplotlib inline&#xff1a;这是默认的模式&#xff0c;输出的图片…

vscode ctrl+鼠标左键无法跳转

打开设置&#xff0c;搜索intel…… 将这个智能感知改成default就可以了&#xff0c;我之前是在disable处。 分析了一下&#xff0c;其实跳转功能主要是根据上下文语法分析来实现的&#xff0c;并不是简单得全文匹配&#xff0c;因此需要相关得语法分析工具。 那么为什么默认式…

异步时序逻辑电路分析

270页异步时序逻辑电路例题分析 阎石数电-第六章时序逻辑电路-6.2.3异步时序逻辑电路分析方法-例题6.2.4

操作系统入门系列-MIT6.828(操作系统工程)学习笔记(三)---- xv6初探与实验一(Lab: Xv6 and Unix utilities)

系列文章目录 操作系统入门系列-MIT6.S081&#xff08;操作系统&#xff09;学习笔记&#xff08;一&#xff09;---- 操作系统介绍与接口示例 操作系统入门系列-MIT6.828&#xff08;操作系统工程&#xff09;学习笔记&#xff08;二&#xff09;----课程实验环境搭建&#x…

【文末附gpt升级秘笈】埃隆·马斯克芯片调配策略对特斯拉股价的影响分析

埃隆马斯克芯片调配策略对特斯拉股价的影响分析 一、引言 在现代商业环境中&#xff0c;企业间的资源调配与策略布局往往对其股价产生深远影响。据外媒CNBC报道&#xff0c;埃隆马斯克在芯片资源分配上的决策引起了业界的广泛关注。他秘密要求英伟达将原本预留给特斯拉的高端…

苹果Vision Pro 界面中英翻译

目录 菜单 &#x1f537;General&#x1f504;一般 AirDrop 隔空投送 Background App Refresh 后台应用刷新 Keyboards 键盘 VPN & Device Management VPN与设备管理​编辑Legal & Regulatory 法律法规 &#x1f537;Apps&#x1f504;应用程序 &#x1f537;Pe…

飞睿智能工业无线通信模块图传WiFi,地对空图传超5km,4堵实墙穿透稳定传输

在当今高科技飞速发展的时代&#xff0c;远距离无线通信技术的应用越来越广泛&#xff0c;尤其是在地对空通信领域。今天&#xff0c;我们将深入探讨一种远距离无线通信模块WiFi图传&#xff0c;它不仅能实现地对空远距离图传超过5公里&#xff0c;还具备穿透4堵实墙的穿墙效果…

Qt Creator常用的快捷键和常用功能

常用快捷键 新建项目&#xff0c;ctrl n 运行项目&#xff0c;ctrl r 构建项目&#xff0c;ctrl b 改变编辑器界面字体显示比例大小&#xff0c;ctrl 鼠标滚轮 对齐代码&#xff0c;ctrl a; ctrl i 跳转到上一行&#xff0c;ctrl shift enter 跳转到下一行&#xff0c;…

PHP实现一个简单的接口签名方法以及思路分析

文章目录 签名生成说明签名生成示例代码签名校验示例代码 签名生成说明 B项目需要调用A项目的接口&#xff0c;由A项目为B项目分配 AccessKey 和 SecretKey&#xff0c;用于接口加密&#xff0c;确保不易被穷举&#xff0c;生成算法不易被猜测。 最终需要确保包含签名的参数只…

vscode 编程工具配置Java开发环境

vs code 开发环境配置。 环境准备&#xff1a; 1. 安装JDK/安装maven/安装vs code 首先安装好vs code 之后&#xff0c;需要安装 Extension Pack for Java 这么个插件 配置maven&#xff0c;进入setting&#xff0c; 3&#xff1a;配置 maven安装目录&#xff0c;4&#xff1a…

超详细!新手入门PMP®考试指南,收藏起来备考更高效​!

回复数字“6”&#xff0c;查看PMP考试过关口诀 无论你是刚刚踏入项目管理领域的新手&#xff0c;对于PMP考试充满好奇与期待&#xff1b; 还是已经在职场中摸爬滚打多年&#xff0c;希望通过PMP认证来进一步提升自己的项目管理能力和职业竞争力。 相信这份指南都会为你提供…

react 中使用 swiper

最近项目中需要用到轮播图&#xff0c;我立马想起了 swiper &#xff0c;那么本文就来带大家体验一下如何在 React 中使用这个插件&#xff0c;使用的是 函数组 hooks 的形式。 需求非常简单&#xff0c;就是一个可以自动播放、点击切换的轮播图&#xff08;跑马灯&#xff0…

UDSonCAN刷写之StayInBOOT和FlashDiver

目录 0 前言 1 StayInBOOT 2 Flash Driver 0 前言 最近在做刷写相关的工作&#xff0c;顺便搞懂了StayInBOOT和FlashDiver&#xff0c;写出来作为分享&#xff0c;如果有哪里不对也请多多指正。 1 StayInBOOT StayInBOOT在整个流程中的位置如下图所示&#xff0c;从图中可…