关于nosql----mongodb的基本使用

  作为nosql中的重要一员,mongodb基于其强大的拓展性,高性能写入读取,易分片等优势对传统的关系型数据库如mysql发起了挑战,但传统数据库还是有一定的优势,如技术成熟度,事务支持等,我认为学习数据库对nosql的了解是必不可少的,而mongodb是其入门的最好的磨刀石。

  下面来使用一下基本的增删改查命令:

查询所有命令:db.col.find().pretty();

其实查询还有多种玩法,如db.col.find({likes: {$gt:503}, $or: [{by: "菜鸟教程"},{title: "MongoDB 教程"}]}).pretty()

gt表示大于,gte表示大于等于,lt表示小于,lte表示小于等于,这条语句是对应的sql是likes>503 and(by='菜鸟教程' or title='MongoDB 教程')。还可以使用类似sql语言中的sum count,avg等,这里不再详细讲述了。。。。


增加命令:db.col.insert({title:'justtest',by:'nullguo',likes:'999'});


再次查询一下,看看是否成功


成功了,nosql数据库最大的优势就是它是面向文档存储的,不会把数据库记录固定在某一table格式下,而是以collections作为一个相关数据的集合,集合一般有相似的特点才被存放在一起。

删除命令:db.col.deleteMany({title:{$regex:'just'}})

mongodb支持正则表达式,使用$regex即可


刚才新增的数据已经被删除了。

  修改:db.col.update({'title':'java 教程'},{$set:{'title':'MongoDB','likes':22222}},false,true)

后面的false,true是表示不新增并且全部符合要求的数据都修改,

结果是


再看看java中怎么使用mongodb

首先导入包

    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver</artifactId>
      <version>3.4.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>bson</artifactId>
      <version>3.4.1</version>
      <scope>compile</scope>
    </dependency>

  连接mongodb生成mongodbclient和mongodbdatabase

 

	static final String DBName = "nullguo";
    public MongoClient getMongoClient(){
        MongoClient mongoClient = null;
        try {
              // 连接到 mongodb 服务
            mongoClient = new MongoClient("localhost",27017); 
            System.out.println("Connect to mongodb successfully");
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return mongoClient;
    }

    public MongoDatabase getMongoDataBase(MongoClient mongoClient) {  
        MongoDatabase mongoDataBase = null;
        try {  
            if (mongoClient != null) {  
                  // 连接到数据库
                mongoDataBase = mongoClient.getDatabase(DBName);  
                System.out.println("Connect to DataBase successfully");
            } else {  
                throw new RuntimeException("MongoClient不能够为空");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return mongoDataBase;
    }  

连接需要被操作的collections

 MongoCollection<Document> collection = mongoDataBase.getCollection("col");

查询操作:

  FindIterable<Document> findIterable = collection.find();  
     MongoCursor<Document> mongoCursor = findIterable.iterator();  
     while(mongoCursor.hasNext()){  
        System.out.println(mongoCursor.next());  
    }

结果


增加操作:

 Document document = new Document("title", "MongoDB").  
                append("description", "database").  
                append("likes", 100).  
                append("by", "Fly").
                append("coder", "nullguo");  
List<Document> documents = new ArrayList<Document>();  
documents.add(document);  
collection.insertMany(documents); 

修改操作:

collection.updateMany(new Document("url",new Document("$regex","runoob")), new Document("$set",new Document("url","nullguo")));

删除操作:

collection.deleteMany(new Document("description",new Document("$regex","Nosql")));


只剩下一条数据记录了。。。

还有如果一条document中有documentlist的话要这样做:

测试,先插入一条数据记录:

        List<Document> members = new ArrayList<Document>();  
        members.add(new Document("id","12553"));
        members.add(new Document("id","12345"));
        Document document = new Document("title", "MongoDB").  
                append("description", "database").  
                append("likes", 100).  
                append("by", "Fly").
                append("coder",members);  
                List<Document> documents = new ArrayList<Document>();  
                documents.add(document);  
                collection.insertMany(documents); 

当遍历数据记录时,可用instanceof来判断coder是否为List<?>,再去安全地强制转换对象类型,为什么不是去判断List<Document>?因为泛型会在运行期把类型擦除,List里面是什么的类型其实已经无法判断了。详情可去搜索java泛型原理。。

  

    FindIterable<Document> findIterable = collection.find();  
     MongoCursor<Document> mongoCursor = findIterable.iterator();  
     while(mongoCursor.hasNext()){   
    	Object object=mongoCursor.next().get("coder");
        if( object instanceof List<?>) {
        	List<Document> list=(List<Document>)object;
        	for (int i = 0; i < list.size(); i++) {
				System.out.println(list.get(i).get("id"));
			}
        }
    }

结果已经出来了,利用这样的存储机制,其实对json类型的数据mongodb有着强大的支持,爬虫和mongodb应该是天作之合吧。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值