当前位置: 首页>数据库>正文

mongodb nearest url怎么配置 mongodb rs.add

pom.xml引入jar

<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>4.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.8.2</version>
        </dependency>

JAVA MongoApi 操作

Java连接MongoDB

public static void main(String[] args) {
        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            //ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress("172.16.131.156",27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential("tbook", "STC", "tbook".toCharArray());
//            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
//            credentials.add(credential);
            MongoClientOptions.Builder build = new MongoClientOptions.Builder();
            build.connectionsPerHost(50); //与目标数据库能够建立的最大connection数量为50
            build.maxWaitTime(2*60*1000);
           ;
            build.threadsAllowedToBlockForConnectionMultiplier(50); //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
            build.connectTimeout(1000*60*1); //与数据库建立连接的timeout设置为1分钟
            build.localThreshold(15000);
            build.maxConnectionIdleTime(6000);
            build.socketTimeout(60000);
            MongoClientOptions myOptions = build.build();
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs,credential,myOptions);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("STC");
            System.out.println("Connect to database successfully");
//            insertWhere(mongoDatabase);
//            query(mongoDatabase);
//            queryWhere(mongoDatabase);
//            insertWhere(mongoDatabase);
//            updateWhere(mongoDatabase);
            findOneUpdate(mongoDatabase);
        } catch (Exception e) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }

查询

集合查询 find
// table 为集合
mongoDatabase.getCollection(table).find()
查询集合的总数量 countDocuments
// table 为集合
mongoDatabase.getCollection(table).countDocuments()

按条件查询

单条件查询 Filters.eq
Bson bson =  Filters.eq("name",1);
 mongoDatabase.getCollection(table).find(bson);
单条件查询数量 countDocuments
Bson bson =  Filters.eq("name",1);
 mongoDatabase.getCollection(table).countDocuments(bson);
多条件查询 Filters.and
Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
 mongoDatabase.getCollection(table).find(bson);
多条件查询数量 countDocuments
Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
 mongoDatabase.getCollection(table).countDocuments(bson);
查询返回指定字段 projection
Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
FindIterable<Document> tbook = mongoDatabase.getCollection(table).find().projection(bson);
查询并排序 sort
//-1 为倒序  1为正序
Bson sort = Filters.eq("time",-1);
FindIterable<Document> tbook1 = mongoDatabase.getCollection(table).find().sort(sort);
按条件,时间区间查询并排序
// Filters.eq 条件匹配   Filters.gte  大于  Filters.lte  小于

Bson filter =Filters.and(Filters.eq("securityID", "TS2306"),Filters.gte("createTime", "2022-10-19 00:00:00.000"),Filters.lte("createTime", "2022-10-19 23:59:59.999")) ;
Bson sort = Filters.eq("time",-1);
FindIterable<Document> tbook = mongoDatabase.getCollection(table).find(filter).sort(sort);
模糊查询 regex
Bson filter = Filters.regex("name", "小明");
mongoDatabase.getCollection("test").find(filter);
分页查询 skip,limit
//skip 跳多少行,limit看多少数据
Bson filter = Filters.regex("name", "小明");
mongoDatabase.getCollection("test").find(filter).skip(2).limit(10);

添加

单条添加 insertOne
Document document = new Document();
document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
mongoDatabase.getCollection("test").insertOne(documents);
多条添加 insertMany
List<Document> documents = new ArrayList<>();
Document document = new Document();
document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
Document document1 = new Document();
document1.append("name","小红").append("age",10).append("sex","女").append("time","2022-10-18 17:45:06.460");
documents.add(document);
documents.add(document1);
mongoDatabase.getCollection("test").insertMany(documents);

修改

有就修改,没有就添加 findOneAndUpdate
// true 为默认添加,false为不添加
Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
Document document = new Document();
document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
Document oneAndUpdate = mongoDatabase.getCollection("test").findOneAndUpdate(filter, new Document().append("$set", document), new FindOneAndUpdateOptions().upsert(true));
修改单条 updateOne
Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
Document document = new Document();
document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
mongoDatabase.getCollection("test").updateOne(filter,new Document().append("$set", document));
修改多条 updateMany
Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
Document document = new Document();
document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));

删除数据

删除单个数据 deleteOne
Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
mongoDatabase.getCollection("test").deleteOne(filter);
删除多个数据 deleteMany
Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
mongoDatabase.getCollection("test").deleteMany(filter);

JAVA代码展示

package test;

import com.mongodb.*;
import com.mongodb.client.ClientSession;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Authentication {
    public static String table = "test";
    public static void main(String[] args) {
        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            //ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress("172.16.131.156",27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential("tbook", "STC", "tbook".toCharArray());
//            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
//            credentials.add(credential);
            MongoClientOptions.Builder build = new MongoClientOptions.Builder();
            build.connectionsPerHost(50); //与目标数据库能够建立的最大connection数量为50
            build.maxWaitTime(2*60*1000);
           ;
            build.threadsAllowedToBlockForConnectionMultiplier(50); //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
            build.connectTimeout(1000*60*1); //与数据库建立连接的timeout设置为1分钟
            build.localThreshold(15000);
            build.maxConnectionIdleTime(6000);
            build.socketTimeout(60000);
            MongoClientOptions myOptions = build.build();
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs,credential,myOptions);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("STC");
            System.out.println("Connect to database successfully");
//            insertWhere(mongoDatabase);
//            query(mongoDatabase);
//            queryWhere(mongoDatabase);
//            insertWhere(mongoDatabase);
//            updateWhere(mongoDatabase);
            findOneUpdate(mongoDatabase);
        } catch (Exception e) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }

    //查询
    public static void query(MongoDatabase mongoDatabase){
        mongoDatabase.getCollection(table).countDocuments();
        Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));

        FindIterable<Document> tbook = mongoDatabase.getCollection(table).find().projection(bson);
        tbook.forEach((Block<? super Document>) document -> {
            System.out.println(document.get("name"));
        });
        Bson sort = Filters.eq("time",-1);
        FindIterable<Document> tbook1 = mongoDatabase.getCollection(table).find().sort(sort);
        tbook1.forEach((Block<? super Document>) document -> {
            System.out.println(document);
        });
    }

    //条件查询
    public static void queryWhere(MongoDatabase mongoDatabase){
        Bson filter =Filters.and(Filters.eq("securityID", "TS2306"),
                Filters.gte("createTime", "2022-10-19 00:00:00.000"),
                Filters.lte("createTime", "2022-10-19 23:59:59.999")) ;
        Bson sort = Filters.eq("time",-1);
        FindIterable<Document> tbook = mongoDatabase.getCollection(table).find(filter).sort(sort);
        long countDocuments = mongoDatabase.getCollection(table).countDocuments(filter);
        System.out.println(countDocuments);
        tbook.forEach((Block<? super Document>) document -> {
            System.out.println(document);
        });
    }

    //条件查询
    public static void updateWhere(MongoDatabase mongoDatabase){
        Bson filter =Filters.and(Filters.eq("_id", new ObjectId("63579bcd4d01156a58abfc1e"))) ;
        Document document = new Document();
        document.append("name","小小红").append("age",10).append("sex","女");
        UpdateResult updateResult = mongoDatabase.getCollection("test").updateOne(filter,  new Document("$set", document));
            System.out.println(updateResult.getModifiedCount());
    }
    //条件查询
    public static void findOneUpdate(MongoDatabase mongoDatabase){
        Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
        Document document = new Document();
        document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
        Document oneAndUpdate = mongoDatabase.getCollection("test").findOneAndUpdate(filter, new Document().append("$set", document), new FindOneAndUpdateOptions().upsert(true));
        mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));
        System.out.println(oneAndUpdate);
    }

    //修改
    public static void updateOneMany(MongoDatabase mongoDatabase){
        Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
        Document document = new Document();
        document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
        mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));
        mongoDatabase.getCollection("test").updateOne(filter,new Document().append("$set", document));
    }

    //修改
    public static void deleteOneMany(MongoDatabase mongoDatabase) {
        Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
        mongoDatabase.getCollection("test").deleteMany(filter);
        mongoDatabase.getCollection("test").deleteOne(filter);
    }

    //模糊查询
    public static void likeQuery(MongoDatabase mongoDatabase) {
        Bson filter = Filters.regex("name", "小明");
        mongoDatabase.getCollection("test").find(filter).skip(2).limit(10);
        mongoDatabase.getCollection("test").find(filter);
    }

    //条件查询
    public static void insertWhere(MongoDatabase mongoDatabase){
        List<Document> documents = new ArrayList<>();
        Document document = new Document();
        document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
        Document document1 = new Document();
        document1.append("name","小红").append("age",10).append("sex","女").append("time","2022-10-18 17:45:06.460");
        documents.add(document);
        documents.add(document1);
        mongoDatabase.getCollection("test").insertMany(documents);

    }
}



https://www.xamrdz.com/database/6mc1962877.html

相关文章: