Java连接MnogoDb数据库

来源:互联网 发布:倚天行情软件下载 编辑:程序博客网 时间:2024/06/06 00:17

添加:mongo-java-driver-3.2.2.jar   驱动地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/


主要代码:

 //我的mongoDb 没有密码
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        // 连接到数据库//如果选择的数据库是不存在的则自动创建数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("huang");
        System.out.println("Connect to database successfully");
        //选择集合  //如果集合不存在则创建这个集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("linqing");
        System.out.println("选择集合成功");
//      mongoDatabase.createCollection("testhuang");
//      System.out.println("集合创建成功");
        //插入文档
        /**
         * 1. 创建文档 org.bson.Document 参数为key-value的格式
         * 2. 创建文档集合List<Document>
         * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
         * */
        Document document = new Document("name", "huanglinqing").
                append("sex", "man").
                append("age", 22).
                append("like", "handsome");
        List<Document> documents = new ArrayList<Document>();
        documents.add(document);
        collection.insertMany(documents);
        System.out.println("文档插入成功");
        //检索所有文档
        /**
         * 1. 获取迭代器FindIterable<Document>
         * 2. 获取游标MongoCursor<Document>
         * 3. 通过游标遍历检索出的文档集合
         * */
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while(mongoCursor.hasNext()){
            System.out.println(mongoCursor.next());
        }
        //更新文档   将文档中likes=100的文档修改为likes=200
        collection.updateMany(Filters.eq("age", 22), new Document("$set",new Document("age",19)));
        //检索查看结果
        FindIterable<Document> findIterable1 = collection.find();
        MongoCursor<Document> mongoCursor1 = findIterable1.iterator();
        while(mongoCursor1.hasNext()){
            System.out.println(mongoCursor1.next());
        }
        //删除
        //删除符合条件的第一个文档
//        collection.deleteOne(Filters.eq("likes", 200));
//        //删除所有符合条件的文档
//        collection.deleteMany (Filters.eq("likes", 200));

源码位置:https://github.com/huanglinqing123/Java_Connect_MongoDb.git


原创粉丝点击