zoukankan      html  css  js  c++  java
  • MongoDB简单的增删改查

    首先引入mongoDB的jar包

    <dependencies>

       <dependency>

         <groupId>org.mongodb</groupId>

        <artifactId>mongo-java-driver</artifactId>

        <version>3.0.4</version>

      </dependency>

    </dependencies>

    连接数据库:
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    两个参数都可以不填,默认是localhost合27017

    获取数据表

    MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

    获取集合

    MongoCollection<Document> collection = MongoDBUtil.getConnect().getCollection("user");

    这几个方法可以进行封装方便使用

    查询:

    Bson filter = Filters.eq("name", "张三");
    //指定查询过滤器查询
    FindIterable findIterable = collection.find(filter);
    MongoCursor cursor = findIterable.iterator();
    while (cursor.hasNext()) {
    System.out.println(cursor.next());
    }

    添加

    Document document = new Document("name","张三")
    .append("sex", "男")
    .append("age", 18);
    //插入一个文档
    collection.insertOne(document);

    修改

    Bson filter = Filters.eq("name", "张三");
    //指定修改的更新文档
    Document document = new Document("$set", new Document("age", 100));
    //修改单个文档
    collection.updateOne(filter, document);

    注意,在新版mongoDB中,也许是更新策略变化,updateOne改用replaceOne使用

  • 相关阅读:
    设计模式学习——前言和目录
    模板颜色搭配
    win7、xp下Meclipse SVN用户名修改
    JS编码解码
    用Javascript进行HTML转义(分享)
    打印异常信息
    lucene 抛出的异常(分享)
    SQL语句优化(分享)
    Java集群之session共享解决方案
    VUE中返回上一页
  • 原文地址:https://www.cnblogs.com/jinsheng1027/p/11792357.html
Copyright © 2011-2022 走看看