IDEA Maven用Java实现Mongo增删改查

准备Mongo数据库

Docker连编部署mongo yml部署

创建Mongo数据库

use skedu

IDEA创建Maven项目

new project ------> Maven ------->Create from archetype 
//选择自动导入
org.apache.maven.archetypes:maven-archetype-quickstart

在这里插入图片描述

编辑pol.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mongodb</groupId>
    <artifactId>mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.10.1</version>
        </dependency>
    </dependencies>


</project>

右下角弹出窗口 选择自动下载更新包

App.java

package mongotest;

import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

/**
 * Java + MongoDB Hello world Example
 *
 */
public class App {
    public static void main(String[] args) {

        try {

            /**** Connect to MongoDB ****/
            // Since 2.10.0, uses MongoClient
            MongoClient mongo = new MongoClient("localhost", 16161);

            /**** Get database ****/
            // if database doesn't exists, MongoDB will create it for you
            DB db = mongo.getDB("skedu");

            //DBCollection coll = (DBCollection) db.createCollection("student");

            /**** Get collection / table from 'testdb' ****/
            // if collection doesn't exists, MongoDB will create it for you
            DBCollection table = db.getCollection("student");



            /**** Insert ****/
            // create a document to store key and value
            BasicDBObject document = new BasicDBObject();
            document.put("sname", "mkyong");
            document.put("sage", 18);
            document.put("sex", "man");
            table.insert(document);

            /**** Find and display ****/
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("sname", "mkyong");

            DBCursor cursor = table.find(searchQuery);

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

            /**** Update ****/
            // search document where name="mkyong" and update it with new values
            BasicDBObject query = new BasicDBObject();
            query.put("sname", "mkyong");

            BasicDBObject newDocument = new BasicDBObject();
            newDocument.put("sname", "mkyong-updated");

            BasicDBObject updateObj = new BasicDBObject();
            updateObj.put("$set", newDocument);

            table.update(query, updateObj);




            /**** Find and display ****/
            System.out.println("111111111111");
            BasicDBObject searchQuery2
                    = new BasicDBObject().append("sname", "mkyong-updated");

            DBCursor cursor2 = table.find(searchQuery2);

            while (cursor2.hasNext()) {
                System.out.println("111111111111");

                System.out.println(cursor2.next());
            }

            /**** Done ****/
            System.out.println("Done");

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }

    }
}

在这里插入图片描述

Navicat检查

在这里插入图片描述

============================================================

插入多条信息

============================================================

package mongotest;

import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.*;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

/**
 * Java + MongoDB Hello world Example
 *
 */
public class App {
    public static void main(String[] args) {

        try {

            /**** Connect to MongoDB ****/
            // Since 2.10.0, uses MongoClient
            MongoClient mongo = new MongoClient("localhost", 16161);

            /**** Get database ****/
            // if database doesn't exists, MongoDB will create it for you
            DB db = mongo.getDB("skedu");

            //DBCollection coll = (DBCollection) db.createCollection("student");

            /**** Get collection / table from 'testdb' ****/
            // if collection doesn't exists, MongoDB will create it for you
            DBCollection table = db.getCollection("book");

            /**
             * db.books.insertMany([
             * {
             * bname:"java",
             * price:20,
             * number:5,
             * status:"在售"
             *
             * },
             * {
             * bname:"oracle",
             * price:30,
             * number:5,
             * status:"缺货"
             * }
             * ])
             * **/
            BasicDBObject document1 = new BasicDBObject();
            document1.put("bname", "java");
            document1.put("price", 20);
            document1.put("number", 5);
            document1.put("status", "缺货");
            table.insert(document1);

            BasicDBObject document2 = new BasicDBObject();
            document2.put("bname", "oracle");
            document2.put("price", 30);
            document2.put("number", 5);
            document2.put("status", "缺货");
            table.insert(document2);

            /**** Insert ****/
            // create a document to store key and value
/*            BasicDBObject document = new BasicDBObject();
            document.put("sname", "mkyong");
            document.put("sage", 18);
            document.put("sex", "man");
            table.insert(document);*/

            /**** Find and display ****/
/*            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("sname", "mkyong");*/

            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("bname", "java");

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            BasicDBObject searchQuery2 = new BasicDBObject();
            searchQuery.put("bname", "oracle");

            DBCursor cursor2 = table.find(searchQuery);

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

            /**** Update ****/
            // search document where name="mkyong" and update it with new values
            BasicDBObject query = new BasicDBObject();
            query.put("bname", "oracle");

            BasicDBObject newDocument = new BasicDBObject();
            newDocument.put("bname", "oracle2");

            BasicDBObject updateObj = new BasicDBObject();
            updateObj.put("$set", newDocument);

            table.update(query, updateObj);




            /**** Find and display ****/
            BasicDBObject searchQuery9
                    = new BasicDBObject().append("bname", "oracle2");

            DBCursor cursor9 = table.find(searchQuery9);

            while (cursor9.hasNext()) {


                System.out.println(cursor9.next());
            }

            /**** Done ****/
            System.out.println("Done");

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }

    }
}

在这里插入图片描述
在这里插入图片描述

发布了154 篇原创文章 · 获赞 605 · 访问量 23万+
展开阅读全文

我的maven项目连接mongodb出现链接异常

12-14

以前还好用,也插入过数据,但是今天就不行了。 项目是maven项目,连接的mongodb在远程服务器上,而且远程服务器的ip和我的ip不在一个网段内, 我改了ip和远程服务器在一个网段后,能ping通远程服务器,但是不能上网了。就出现了mongodb连接超时 具体异常如下 com.mongodb.MongoSocketOpenException: Exception opening socket at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) [mongodb-driver-core-3.1.0.jar:?] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_40] Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[?:1.8.0_40] at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[?:1.8.0_40] at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[?:1.8.0_40] at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[?:1.8.0_40] at java.net.Socket.connect(Socket.java:589) ~[?:1.8.0_40] at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.1.0.jar:?] ... 3 more 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览