3. mongodb Java编写代码操作

Posted unclecc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. mongodb Java编写代码操作相关的知识,希望对你有一定的参考价值。

0. 默认使用Maven

<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.10.2</version>
</dependency>

1. 代码

package com.chenwen;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.WriteModel;
import org.bson.BasicBSONObject;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import java.util.*;

/**
 * TestMongodb
 *
 * @author chenwen
 * @desc
 * @Date 2019/7/29 11:25
 */
public class TestMongodb 


    private MongoCollection<Document> mongoCollection;
    private Random random = new Random();

    @Before
    public void init() 
        MongoClient mongoClient = new MongoClient("192.168.255.157", 27017);
        MongoDatabase database = mongoClient.getDatabase("test");
        mongoCollection = database.getCollection("col");
    

    /**
     *
     * 插入单条
     *
     */
    @Test
    public void testInsertOne() 
        Document document = new Document();
        document.append("userId",0);
        document.append("userName", "test0");
        document.append("age", 12);
        document.append("birthday", new Date());
        mongoCollection.insertOne(document);
    


    /**
     *
     * 简单查询
     *
     */
    @Test
    public void testSimpleQuery() 
        BasicDBObject basicDBObject = new BasicDBObject();
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.set(Calendar.HOUR_OF_DAY, 12);
        Date time = instance.getTime();
        // 虽然mongodb是UTC时间, 但你传Date类型进行查询, 他会自动转换的;
        basicDBObject.append("birthday", new BasicBSONObject("$gt", time));
        FindIterable<Document> documents = mongoCollection.find(basicDBObject);
        MongoCursor<Document> iterator = documents.iterator();
        while(iterator.hasNext()) 
            System.out.println(iterator.next().toJson());
        
    

    /**
     *
     * 批量插入
     *
     */
    @Test
    public void testInsertMany() 
        List<Document> documents = new ArrayList<>();

        for (int i = 0; i < 100; i++) 
            Document document = new Document();
            document.append("userId",i);
            document.append("userName", "test" + i);
            document.append("age", random.nextInt(30));
            document.append("birthday", new Date());
            documents.add(document);
        

        mongoCollection.insertMany(documents);
    

    /**
     * 删除全部
     */
    @Test
    public void testDelete() 
        // db.collection.remove();
        BasicDBObject basicDBObject = new BasicDBObject();
        mongoCollection.deleteMany(basicDBObject);
    


    /**
     *
     * 批量操作
     *
     */
    @Test
    public void bulkWrite() 

        List<WriteModel<Document>> writeModels = new ArrayList<>();
        // 插入
        Document document = new Document();
        document.append("test", 1);
        InsertOneModel insertOneModel = new InsertOneModel(document);
        writeModels.add(insertOneModel);

        // 修改
        Document query = new Document("test", 1);
        Document update = new Document("$set", new Document("test", 3));
        UpdateManyModel updateManyModel = new UpdateManyModel(query, update);
        writeModels.add(updateManyModel);

        mongoCollection.bulkWrite(writeModels);
    




## 3. 驱动工作原理
所有的mongodb驱动都执行三个主要的功能:
- 1. 生成mongodb对象的Id, 默认存储在所有文档的_id字段.
- 2. 驱动会把任意的语言表示的文档对象转换为BSON或者从BSON转换回来.
- 3. 使用Mongodb的自定义协议的TCP Socket连接与数据库通信.

_id 结构: 4B时间 + 机器ID + 进程ID + 计数器
在驱动生成_id的好处之一就是防止自增主键使MongoDB产生性能瓶颈. 












以上是关于3. mongodb Java编写代码操作的主要内容,如果未能解决你的问题,请参考以下文章

Java操作MongoDB的增删改查,完整项目分享

node.js零基础详细教程:node.js操作mongodb,及操作方法的封装

MongoDB-JAVA-Driver 3.2版本常用代码全整理 - 增删改

Java读取MongoDB数据库值

java编写代码两个放到同个包中一起运行,怎么操作

php操作mongoDB数据库查询的时候怎样写“或”这样的多个条件查询代码?