Java操作Mongodb数据库

Mongodb提供Java Api来进行数据操作。使用方法很简单,在java编译路径中包含mongo.jar文件即可,如果使用maven,直接添加mongo依赖即可。

建立连接

建立MongoDB连接,需要一个数据库名字,数据库如果不存在,mongodb会自动创建该数据库。

创建MongodClient的构造函数:

MongoClient mongoClient = new MongoClient();
MongoClient mongoClient = new MongoClient( "localhost" );
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                  new ServerAddress("localhost", 27018),
                                  new ServerAddress("localhost", 27019)));

DB db = mongoClient.getDB( "mydb" );  

下面是个简单的例子:

package com.yeetrack.mongo.test;

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

import org.bson.NewBSONDecoder;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;

public class MyMongodbTest
{

    /**
     * 学习mongodb java Driver
     * @author youthflies
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException
    {
        //实例化一个mongod客户端
        MongoClient mongoClient = new MongoClient("192.1.219.163", 27017);

        //遍历全部的库
        for(String string : mongoClient.getDatabaseNames())
            System.out.println("mongodb数据库名字--->"+string);

        //使用用户名、密码登陆
        boolean auth = db.authenticate(myUserName, myPassword);
        //获取数据库对象
        DB db = mongoClient.getDB("mydb");

        //打印mydb库中的所有数据集名字
        Set<String> colls = db.getCollectionNames();
        for(String s : colls)
            System.out.println("库中数据集名字--->"+s);

        //获得指定的数据集
        DBCollection collection = db.getCollection("user");

        mongoClient.setWriteConcern(WriteConcern.JOURNALED);

        //插入一条数据
        // {"name":"Lily", "age":"18"}
        BasicDBObject basicDBObject = new BasicDBObject("name", "Lily").
                                        append("age", "18");
        //collection.insert(basicDBObject);
        //再插入一条数据
        //{"name":"Boss", "age":"33", "boys":{"name","boy1":
        BasicDBObject basicDBObject2 = new BasicDBObject("name", "Boss").
                                        append("age", "44").
                                        append("kids", new BasicDBObject("name", "son").append("age", "11"));

        //collection.insert(basicDBObject2);

        //获取数据集中的第一条数据
        DBObject myDbObject = collection.findOne();
        System.out.println(myDbObject);

        //使用循环向mongo中插入数据
        for(int i=0;i<=4;i++)
        {
            //collection.insert(new BasicDBObject("name","loop").append("age", i));
        }

        //获取数据集中的数据个数
        System.out.println("数据集中共有数据--->"+collection.getCount());

        //使用游标DBCursor
        DBCursor cursor = collection.find();
        try
        {
            while(cursor.hasNext())
            System.out.println(cursor.next());
        } finally
        {
            cursor.close(); //关闭游标
        }

        //指定检索条件,例如 name=Lily
        BasicDBObject queryBasicDBObject  = new BasicDBObject("name", "Lily");
        DBCursor cursor2 = collection.find(queryBasicDBObject);

        try
        {
            while(cursor2.hasNext())
                System.out.println("检索结果--->"+cursor2.next());
        } finally
        {
            cursor2.close();
        }

        //指定检索条件时,使用$高级查询
        // mongodb命令:db.user.find({"name":{$ne:"Lily"},"age":{$gt:"12"}}) 查询名字不是lily,且age大于12的用户
        BasicDBObject queryBasicDBObject2 = new BasicDBObject("name", new BasicDBObject("$ne", "Lily")).
                                            append("age", new BasicDBObject("$gt", "12"));
        DBCursor cursor3 = collection.find(queryBasicDBObject2);
        try
        {
            while(cursor3.hasNext())
                System.out.println("查询名字不是lily,且age大于12的用户--->"+cursor3.next());
        } finally
        {
            cursor3.close();
        }
        //$ne:不等于  $gt:大于  $lt:小于   $lte:小于等于            和shell命令一致

        //创建索引,1代表升序,-1代表降序
        collection.createIndex(new BasicDBObject("name", 1));

        //获取索引
        List<DBObject> list = collection.getIndexInfo();
        for(DBObject object : list)
            System.out.println("索引信息--->"+object);

        //删除一个库
        mongoClient.dropDatabase("mydb");

        mongoClient.close();

    }

}
版权声明

本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。

© 空空博客,本文链接:https://www.yeetrack.com/?p=646