Java MongoDB 增删改查

Java操作MongoDB实战
本文介绍如何使用Java语言通过MongoDB Java Driver进行数据库的基本操作,包括连接数据库、插入记录、更新记录、查询记录及删除记录等核心功能。

使用Java语言实现对MongoDB中的增删改查,基本操作如下。

1. 添加MongoDB Java Driver到maven配置中。

      <dependency>
          <groupId>org.mongodb</groupId>
          <artifactId>mongo-java-driver</artifactId>
          <version>2.11.3</version>
      </dependency>

2. 编写对于测试代码:

package org.mongodb;

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * @author: JohnLiu
 */
public class MongoDBClient {

    MongoClient mongo = null;

    public MongoDBClient(){
        try {
            mongo = new MongoClient("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if(mongo != null){
            DB db = mongo.getDB("manager_db");
            //authenticate the user
            System.out.println("auth user 'admin/123456'" +db.authenticate("admin", "123456".toCharArray()));
            //display all the dbs
            List<String> dbList = mongo.getDatabaseNames();
            System.out.println("-----------------show dbs--------------------");
            for(String dbName: dbList){
                System.out.println(dbName);
            }
            /**
             DB db = mongo.getDB("testdb");
             DBCollection table = db.getCollection("user");
             Display all collections from selected database.

             DB db = mongo.getDB("testdb");
             Set<String> tables = db.getCollectionNames();

             for(String coll : tables){
             System.out.println(coll);
             }
             */

        }
    }

    public void insert(){
        DB db = mongo.getDB("manager_db");
        DBCollection table = db.getCollection("user");
        BasicDBObject document = new BasicDBObject();
        document.put("name", "John Nash");
        document.put("age", 26);
        document.put("createdDate", new Date());
        table.insert(document);
        System.out.println("insert successfully..." );
    }

    public void update(){
        DB db = mongo.getDB("manager_db");
        DBCollection table = db.getCollection("user");

        BasicDBObject query = new BasicDBObject();
        query.put("name", "John Nash");

        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "John Liu");

        BasicDBObject updateObj = new BasicDBObject();
        updateObj.put("$set", newDocument);

        table.update(query, updateObj);
        System.out.println("update successfully..." );
    }

    public void query(){
        DB db = mongo.getDB("manager_db");
        DBCollection table = db.getCollection("user");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "John Liu");

        DBCursor cursor = table.find(searchQuery);

        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
        System.out.println("query successfully..." );
    }

    public void remove(){
        DB db = mongo.getDB("manager_db");
        DBCollection table = db.getCollection("user");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "John Liu");

        table.remove(searchQuery);
        System.out.println("remove successfully..." );
    }
    public static void main(String []args){
        MongoDBClient mongoDBClient = new MongoDBClient();
        mongoDBClient.insert();//insert one document to user table
        mongoDBClient.update();
        mongoDBClient.query();
        mongoDBClient.remove();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值