• java对mongodb数据库的简单操作


    准备工作:

      下载好mongodriver.jar包(https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.6.1/)

    代码实现:

    try {
    // 实例化Mongo对象,连接27017端口
    Mongo mongo = new Mongo("localhost", 27017);
    // 连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
    DB db = mongo.getDB("test");
    // Get collection from MongoDB, database named "yourDB"
    // 从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立
    DBCollection collection = db.getCollection("test1");
    // 使用BasicDBObject对象创建一个mongodb的document,并给予赋值。
    BasicDBObject document = new BasicDBObject();
    //document.put("id", 1001);
    //document.put("msg", "hello world mongoDB in Java");
    // 将新建立的document保存到collection中去
    //collection.insert(document);
    // 创建要查询的document
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name", "chen");
    // 使用collection的find方法查找document
    DBCursor cursor =collection.find(searchQuery);
    // 循环输出结果
    while (cursor.hasNext()) {
    System.out.println(cursor.next());
    }
    System.out.println("Hello World");
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (MongoException e) {
    e.printStackTrace();
    }

    可能会遇到的报错信息:

     Note: mongodb-driver requires the following dependencies: bson and mongodb-driver-core

    解决:

    新版本的mongodb的驱动包是依赖bson.jar和mongodb_driver_core.jar的  官网上有提示:
     Note: mongodb-driver requires the following dependencies: bson and mongodb-driver-core 

    去看一下  ,然后对应的地方有两个包的下载,导进你的方法就ok了 

    mongodb-driver-3.0.1.jar

    mongodb-driver-core-3.0.1.jar

    bson-3.0.1.jar

    https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.0.1/

    https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver-core/3.0.1/

    https://oss.sonatype.org/content/repositories/releases/org/mongodb/bson/3.0.1/
  • 相关阅读:
    Linux 安装 jdk 后 jps 出现问题/usr/jdk1.8.0_151/bin/jps: /lib/ld-linux.so.2: bad ELF interpreter: No such
    Jackson 注解
    Git 右键添加Git Bash
    No validator could be found for constraint
    rror querying database. Cause: java.sql.SQLException: null, message from server: "Host '192.168.30.1' is not allowed to connect to this MySQL server"
    Linux 安装 Mysql-5.7.23-linux-glibc2
    Promise
    PAT(B) 1094 谷歌的招聘(Java)
    PAT(B) 1074 宇宙无敌加法器(Java)
    PAT(B) 1078 字符串压缩与解压(Java)
  • 原文地址:https://www.cnblogs.com/g177w/p/8110444.html
Copyright © 2020-2023  润新知