zoukankan      html  css  js  c++  java
  • Java操作MongoDB

    首先是连接到数据库,网上不少博客用的api还是new MongoClient(addrs,credentials)和com.mongodb.DB,这两个api已经过时,被标上横杠杠了,虽然仍然可以用。

    下面是连接数据库的代码:

     1 import com.mongodb.*;
     2 import com.mongodb.client.FindIterable;
     3 import com.mongodb.client.MongoCollection;
     4 import com.mongodb.client.MongoDatabase;
     5 import org.bson.Document;
     6 
     7 public class TestMongo {
     8     public static void main(String[] args) {
     9         /*
    10         * 连接mongo的uri格式:  mongodb://用户名:用户密码@服务器地址:端口/账号登陆的数据库
    11         * 比如这个用户账号是在admin创建的,就要在admin登陆,然后再操作其它数据库
    12         * */
    13         String sURI=String.format("mongodb://%s:%s@%s:%d/%s", "liumaowu", "liumaowu", "localhost", 27017, "admin");
    14         MongoClientURI uri = new MongoClientURI(sURI);
    15         MongoClient mongoClient=new MongoClient(uri);
    16         MongoDatabase db=mongoClient.getDatabase("test_lliumaowu");    //选择要进行操作的数据库
    17         MongoCollection<Document> coll=db.getCollection("test_liumaowu");    //选择要进行操作的集合,我这里集合名和数据库名一样了
    18     }
    19 }

    这是需要验证用户的连接方式,如果不需要验证用户的话,可以直接使用 MongoClient mongoClient=new MongoClient("localhost",27017); 来连接到数据库。

    创建集合使用 db.createCollection("mycoll"); mycoll是集合名

    查询

    1 Document d=new Document().append("grade",16);
    2 FindIterable<Document> documents = coll.find(d);
    3 for(Document doc:documents){
    4   System.out.println(doc);
    5   System.out.println(doc.toJson());
    6   System.out.println(doc.get("_id"));
    7   System.out.println(doc.get("name"));
    8 }
    查询结果如下:
    Document{{_id=5b4d47da6e7761983711e656, name=2b, age=30.0, grade=16.0, friends=[1a, 9n]}}
    { "_id" : { "$oid" : "5b4d47da6e7761983711e656" }, "name" : "2b", "age" : 30.0, "grade" : 16.0, "friends" : ["1a", "9n"] }
    5b4d47da6e7761983711e656
    2b

    我们可以看出,find()方法的返回结果是一种Iterable,Iterable接口只有一个方法Iterator()来转换成Iterator对象。iterable和iterator的区别是:iterable可以使用for each遍历,iterator不可以,必须使用next()、hasNext()方法。

    MongoDB储存数据的格式是bson,是一种很类似json的格式,我们用Document对象来接收查询到的结果,使用get(key值),可以获取想要的数据,也可以把结果转换成json对象。

    如果想要查询全部结果,不加条件的话,可以去掉fin()方法中的参数,如 FindIterable<Document> documents = coll.find(); 

    MongoCollection里面没有findOne()方法了,查一个可以用

    coll.find().limit(1).iterator().next();

    更新

    1 coll.updateOne(new Document("grade",16),new Document("$inc",new Document("grade",5)));
    2 Document d=new Document().append("name","2b");
    3 FindIterable<Document> documents = coll.find(d);
    4 for(Document doc:documents){
    5     System.out.println(doc.toJson());
    6 }

    方便理解的话,这里每有一个new Document 代表mongo中一个花括号,所以update的两个参数代表 .update({"grade",16},{$inc:{"grade":5}}) ,$set同理.

    但是,如果不使用$set或者$inc的话,在mongodb里会直接替换掉原数据,而在java中会报错,想要替换可以使用 coll.findOneAndReplace() 

    删除

    这个有deleteMany和deleteOne方法,与find参数填写方法大同小异。

    添加

    1 Document docInsert=new Document()
    2      .append("name","1a")
    3      .append("age",40)
    4      .append("grade",90);
    5 List<Document> documents=new ArrayList<>();
    6 documents.add(docInsert);
    7 //coll.insertOne(docInsert); 
    8 coll.insertMany(documents);
  • 相关阅读:
    sql 循环表中记录
    asp.net 上传XML,txt 直接读取文件内容
    两个表join 连接,去掉重复的数据
    图片横向显示
    接口测试
    find 命令
    Python 面向对象编程
    python之装饰器、生成器、内置函数、JSON
    python 之常用模块
    python 之函数
  • 原文地址:https://www.cnblogs.com/liumaowu/p/9323826.html
Copyright © 2011-2022 走看看