MongoDB 连接Java

1、创建maven工程


2、pom.xml文件

<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>com.xxx.test</groupId>
  <artifactId>com.xxx.test.db</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
   <name>MongoDBJDBC</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.4.2</version>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>compile</defaultGoal>
    </build>
  
</project>

3、连接Java

package com.xxx.test.db.JDBC;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class App {
	
	public static void main(String[] args) {
		try {
			//连接MongoDB 服务器
			MongoClient mongoClient = 
					new MongoClient("localhost", 27017);
			//连接数据库
			MongoDatabase mDatabase = 
					mongoClient.getDatabase("test");  //test可选
			 
			System.out.println("Connect to database successfully!");
			System.out.println("MongoDatabase inof is : "+mDatabase.getName());
		} catch (Exception e) {
			 System.err.println(
					 e.getClass().getName() + ": " + e.getMessage());
		}
	}

}

运行结果


4、创建集合


package com.xxx.test.db.JDBC;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class CreateCollection {
	
	public static void main(String[] args) {
		try {

            // mongodb server
            MongoClient mongoClient = new MongoClient("localhost", 27017);

            //databases
            MongoDatabase database = mongoClient.getDatabase("test");

            MongoCollection<Document> coll = database.getCollection("myTestCollection");

            System.out.println("Collection created successfully");

            System.out.println("当前数据库中的所有集合是:");

            for (String name : database.listCollectionNames()) {
                System.out.println(name);
            }

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
	}

}

输出结果 :


5、插入文档

package com.xxx.test.db.JDBC;

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class InsertDocument {
	
	public static void main(String[] args) {
		
		 try {

	            // mongodb server
	            MongoClient mongoClient = new MongoClient("localhost", 27017);

	            //databases
	            MongoDatabase database = mongoClient.getDatabase("test");

	            System.out.println("Collection created successfully");

	            System.out.println("当前数据库中的所有集合是:");

	            for (String name : database.listCollectionNames()) {
	                System.out.println(name);
	            }

	            MongoCollection<Document> coll = database.getCollection("test");
	            System.out.println("Collection test selected successfully");
	            MongoCollection<Document> collection = database.getCollection("test");

	            Document document = new Document("_id", 1999).append("title", "MongoDB Insert Demo")
	                    .append("description","database")
	                    .append("likes", 30)
	                    .append("by", "demo point")
	                    .append("url", "http://www.demo.com/mongodb/");

	            collection.insertOne(document);

	            collection.find().forEach(printBlock);

	            System.out.println("Document inserted successfully");

	        } catch (Exception e) {
	            System.err.println(e.getClass().getName() + ": " + e.getMessage());
	        }
	    }

	    static Block<Document> printBlock = new Block<Document>() {
	        public void apply(final Document document) {
	            System.out.println(document.toJson());
	        }
	    };
}


参考资料:https://www.yiibai.com/mongodb/mongodb_java.html

发布了296 篇原创文章 · 获赞 343 · 访问量 104万+
展开阅读全文

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

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

分享到微信朋友圈

×

扫一扫,手机浏览