博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MongoDB编程系列(20)——数据库、集合、文档、键值查询(新老API)
阅读量:7114 次
发布时间:2019-06-28

本文共 5448 字,大约阅读时间需要 18 分钟。

hot3.png

NoSQL数据库的编程就不要去指望JDBC了,MongoDB Java Driver才是我们真正连通MongoDB的java解决方案。

这里我没去github上下载它的源码包,那是gradle管理的,我对groovy不怎么感冒。

于是还是由maven出马吧!

POM如下:

  
4.0.0
  
com.happyBKs.mongodb
  
javamongo
  
0.0.1-SNAPSHOT
  
jar
  
javamongo
  
http://maven.apache.org
  
    
UTF-8
  
  
    
      
junit
      
junit
      
4.10
      
test
    
org.mongodb
mongo-java-driver
3.0.1
  

我再网上搜了一下有关Java使用MongoDB的博客,发现几乎都是老版本的API的调用,新API的很少。

老API调用方式如像下,注意,很多方法和类、接口已经是depreciated了,也就是不推荐使用来了。但是,运行还是没有大问题的,所以我这里也给出来:

package com.happyBKs.mongodb.javamongo;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.Mongo;import com.mongodb.util.JSON;/** * Hello world! * */public class App {    public static void main( String[] args )    {        Mongo mg = new Mongo();        //查询所有的Database        for (String name : mg.getDatabaseNames()) {            System.out.println("dbName: " + name);        }                DB db = mg.getDB("dt2");        //查询所有的聚集集合        for (String name : db.getCollectionNames()) {            System.out.println("collectionName: " + name);        }                DBCollection users = db.getCollection("student");                //查询所有的数据        DBCursor cur = users.find();        while (cur.hasNext()) {            System.out.println(cur.next());        }        System.out.println(cur.count());//        System.out.println(cur.getCursorId());//        System.out.println(JSON.serialize(cur));    }}

新版本的Mongo Java Driver,这里值的是3以后,对调用API进行了重新封装。对照上面的代码,新的类和方法调用如下:

package com.happyBKs.mongodb.javamongo;import java.util.Iterator;import org.bson.BsonDocument;import org.bson.Document;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;public class APP2 {	public static void main(String[] args) {		// TODO Auto-generated method stub		//MongoClient mongoClient2 = new MongoClient("localhost", 27017);		MongoClient mongoClient2 =new MongoClient("localhost", 27017);        //查询所有的Database        for (String name : mongoClient2.listDatabaseNames()) {            System.out.println("dbName: " + name);        }                        MongoDatabase db = mongoClient2.getDatabase("dt2");        //查询所有的聚集集合        for (String name : db.listCollectionNames()) {            System.out.println("collectionName: " + name);        }		        MongoCursor
 it = db.listCollectionNames().iterator(); while(it.hasNext()) { System.out.println(it.next()); } MongoCollection
 users = db.getCollection("student"); //查询所有的数据 注意再泛型参数指定了org.bson.Document MongoCursor
 mcur=users.find().iterator();        while (mcur.hasNext()) {         Document doc=mcur.next();         String name=doc.getString("name");         System.out.println(name);         Double age=doc.getDouble("age");         System.out.println(age);         if(doc.containsKey("phone"))         {             System.out.println("containsKey(phone)");                }         if(doc.containsValue("TB"))         {             System.out.println("containsValue(TB)");             }            System.out.println(doc);        }          Iterator cur = users.find().iterator();        while (cur.hasNext()) {            System.out.println(cur.next());        }         }}

其实功能如其名,我就不多解释了。

这个数据库和集合、文档是以前键好的,开诶看我之前的文章里有。这里我还是写出来吧。

MongoDB shell version: 2.6.8connecting to: test> use dt2switched to db dt2> show collectionsclassstudentsystem.indexes> db.student.find(){ "_id" : ObjectId("54fb0d853fc8173ba3302e6c"), "name" : "Viper", "age" : 20 }{ "_id" : ObjectId("54fb10493fc8173ba3302e6d"), "name" : "TA", "age" : 18, "phone" : [ "1311234567", "021-87658765" ], "GPA" : { "Math" : 88, "English" : 99 } }{ "_id" : 1, "gender" : "male" }{ "_id" : ObjectId("54fc521d3fc8173ba3302e6e"), "name" : "TB", "age" : 22, "gender" : "male", "room" : "301", "classid" : "1515" }>

上面的java新API的运行结果:

dbName: dt4dbName: dt2dbName: dt6dbName: dt3dbName: dt5dbName: localdbName: testdbName: dt1dbName: admincollectionName: studentcollectionName: system.indexescollectionName: classstudentsystem.indexesclassViper20.0Document{
{_id=54fb0d853fc8173ba3302e6c, name=Viper, age=20.0}}TA18.0containsKey(phone)Document{
{_id=54fb10493fc8173ba3302e6d, name=TA, age=18.0, phone=[1311234567, 021-87658765], GPA=Document{
{Math=88.0, English=99.0}}}}nullnullDocument{
{_id=1.0, gender=male}}TB22.0containsValue(TB)Document{
{_id=54fc521d3fc8173ba3302e6e, name=TB, age=22.0, gender=male, room=301, classid=1515}}Document{
{_id=54fb0d853fc8173ba3302e6c, name=Viper, age=20.0}}Document{
{_id=54fb10493fc8173ba3302e6d, name=TA, age=18.0, phone=[1311234567, 021-87658765], GPA=Document{
{Math=88.0, English=99.0}}}}Document{
{_id=1.0, gender=male}}Document{
{_id=54fc521d3fc8173ba3302e6e, name=TB, age=22.0, gender=male, room=301, classid=1515}}

转载于:https://my.oschina.net/happyBKs/blog/425841

你可能感兴趣的文章
jRebel与xRebel的使用
查看>>
Http 协议简略
查看>>
爆炸几何之 CCPC网络赛 I - The Designer (笛卡尔定理)
查看>>
学以致用二---配置Centos7.2 基本环境
查看>>
用php做注册审核
查看>>
实例:使用puppeteer headless方式抓取JS网页
查看>>
一个“MacBook”新手的Python“笨办法”自学之旅 #第六章:常用的简易Python命令、符号、代码、格式化字符串...
查看>>
C++——类的成员函数指针以及mem_fun适配器
查看>>
常州day1p4
查看>>
cuda_c学习笔记-向量加法
查看>>
Spring MVC的总体设计
查看>>
sort命令
查看>>
Alpha 冲刺报告模板
查看>>
SpringBoot中使用JWT
查看>>
poj 3694 Network
查看>>
对象复制问题 && lvalue-rvalue && 引用
查看>>
第十周作业
查看>>
【ABP框架系列学习】N层架构(3)
查看>>
HTML5本地数据库
查看>>
iOS导航栏状态栏相关
查看>>