MongoDB增删改查原生操作


    public static void main(String[] args) {
//        //创建连接对象
//        MongoClient localhost = new MongoClient("localhost", 27017);
//        //获取Mongodb数据库
//        MongoDatabase database = localhost.getDatabase("数据库名");
//        //获取MongoDB中的集合
//        MongoCollection collection = database.getCollection("集合名字");
//        System.out.println("ok = ok");
        MongoDatabase database = MongoDBAuthPoolUtil.getDatabase("数据库名");
        //创建集合(表) 记得确保操作用户的权限是否拥有   集合名字==表明
        database.createCollection("集合名字");
        //获取MongoDB中的集合
        MongoCollection collection = database.getCollection("集合名字");
        //删除MongoDB中的集合
        //collection.drop();
        MongoDBAuthPoolUtil.dropCollection(collection);
        //添加单个文档
        Document document = new Document();
        document.append("key", "value")
                .append("username", "张三")
                .append("age", 22)
                .append("userlike", Arrays.asList(new String[]{"音乐", "篮球"}));
        collection.insertOne(document);
        //添加多个文档
        List<Document> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Document docu = new Document();
            docu.append("key", "value");
            list.add(docu);
        }
        collection.insertMany(list);
        //更新单个文档单个键{$set:{"key","value"}}
        collection.updateOne(Filters.eq("key", "value"), new Document("$set", new Document("key", "value")));
        //更新单个文档多个键
        collection.updateOne(Filters.eq("key", "value"), new Document("$set", new Document("key", "value"))
                .append("key", "value")
                .append("key1", "value1"));
        //更新多个文档中的单个键
        collection.updateMany(Filters.ne("key", null), new Document("$set", new Document("key", "value")));
        //更新多个文档中的多个键
        collection.updateMany(Filters.ne("key", null), new Document("$set", new Document("key", "value"))
                .append("key", "value")
                .append("key1", "value1"));
        //更新文档中的数组
        collection.updateOne(Filters.eq("key", "value"), new Document("$puth", "aa"));
        //查询全部文档,返回的是一个文档的迭代器
        FindIterable<Document> findIterable = collection.find();
        //返回的所有文档的游标
        MongoCursor<Document> cursor = findIterable.iterator();
        //
        while (cursor.hasNext()) {
            Document next = cursor.next();
            System.out.println("next.toJson() = " + next.toJson());
            String key1 = next.getString("key");
            System.out.println("key1 = " + key1);
            Object key = next.get("key");
            System.out.println("key = " + key);
        }

        //通过_id查询文档   注意:这里id类型不是字符串类型  而是 objectId 类型
        FindIterable iterable = collection.find(Filters.eq("_id", new ObjectId("12312sdfa132312ds")));
        MongoCursor<Document> cursor1 = iterable.iterator();
        while (cursor1.hasNext()) {
            Document next = cursor1.next();
            System.out.println("next.toJson() = " + next.toJson());
            String key = next.getString("key");
            System.out.println("key = " + key);
        }
        //根据其他字段查询文档  例: 根据年龄查询,条件是年龄大于19岁的数据
        FindIterable<Document> iterable1 = collection.find(Filters.gt("userAge", "19"));
        MongoCursor<Document> iterator = iterable1.iterator();
        while (iterator.hasNext()) {
            Document next = iterator.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //根据其他字段查询文档  例: 根据年龄查询,条件是年龄是整数
        FindIterable<Document> iterable2 = collection.find(Filters.type("userAge", "number"));
        MongoCursor<Document> iterator2 = iterable1.iterator();
        while (iterator2.hasNext()) {
            Document next = iterator2.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //  查询用户名为 zhangsan lisi 的数据
        FindIterable<Document> iterable3 = collection.find(Filters.in("username", "zhangsan","lisi"));
        MongoCursor<Document> iterator3 = iterable1.iterator();
        while (iterator3.hasNext()) {
            Document next = iterator3.next();
            System.out.println("next.toJson() = " + next.toJson());
        }

        //  查询用户名不为 zhangsan lisi 的数据
        FindIterable<Document> iterable4 = collection.find(Filters.nin("username", "zhangsan","lisi"));
        MongoCursor<Document> iterator4 = iterable1.iterator();
        while (iterator4.hasNext()) {
            Document next = iterator4.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //  查询多个文档  -$regex   条件:查询用户的名字 是z开头  以z结尾 注:其实这里条件只需要更高Pattern.compile()括号内的内容即可
        FindIterable<Document> iterable5 = collection.find(Filters.regex("username", Pattern.compile("^z.*2$")));
        MongoCursor<Document> iterator5 = iterable1.iterator();
        while (iterator5.hasNext()) {
            Document next = iterator5.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //  根据多个条件查询单/多个文档  -$regex   条件:用户名是张三 ,年龄不是18的数据
        FindIterable<Document> iterable6 = collection.find(Filters.and(Filters.eq("username","zhangsan"),Filters.ne("age",18)));
        MongoCursor<Document> iterator6 = iterable1.iterator();
        while (iterator6.hasNext()) {
            Document next = iterator6.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //  根据多个条件查询单/多个文档  -$regex   条件:用户名是张三 ,或者年龄是18的数据
        FindIterable<Document> iterable7 = collection.find(Filters.or(Filters.eq("username","zhangsan"),Filters.eq("age",18)));
        MongoCursor<Document> iterator7 = iterable1.iterator();
        while (iterator7.hasNext()) {
            Document next = iterator7.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //   根据多个条件查询单/多个文档  -$regex   条件:用户名是张三 ,并且年龄是18的数据,或者愛好是唱歌的
        FindIterable<Document> iterable18 = collection.find(Filters.or(Filters.and(Filters.eq("username","zhangsan"),Filters.eq("userage",18)),Filters.eq("like","sing")));
        MongoCursor<Document> iterator18 = iterable1.iterator();
        while (iterator18.hasNext()) {
            Document next = iterator18.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //   根据文档中username是z开头,根据username对结果做降序排序
        FindIterable<Document> iterable9 = collection.find(Filters.regex("username",Pattern.compile("^Z.*"))).sort(new Document("username",-1));
        MongoCursor<Document> iterator9 = iterable1.iterator();
        while (iterator9.hasNext()) {
            Document next = iterator9.next();
            System.out.println("next.toJson() = " + next.toJson());
        }
        //   插入系统日期
        Document docu = new Document();
        docu.put("username","stf");
        docu.put("userage","19");
        docu.put("like",Arrays.asList(new String[]{"sing","eat"}));
        docu.put("date", new Date());
        collection.insertOne(docu);

        //   插入指定日期  插入时间为2022年2月2日2点2分
        Document docus = new Document();
        docus.put("username","stf");
        docus.put("userage","19");
        docus.put("like",Arrays.asList(new String[]{"sing","eat"}));
        Date date = DateUtil.stringToDate("yyyy-MM-dd HH:mm:ss","2022-02-02 02:02:02");
        docus.put("date",date);
        collection.insertOne(docu);

        //查询用户的生日为 2022-02-02 02:02:02 的用户信息
        FindIterable iterable8 = collection.find(Filters.eq("userBirth", date));
        MongoCursor<Document> iterator1 = iterable8.iterator();
        while (iterator1.hasNext()) {
            Document next = iterator1.next();
            String s = next.toJson();
            System.out.println("s = " + s);
        }
        //查询集合中文档的数量  aggregate([{$group:{_id:null,count:{$sum:1}}}])
        Document sum = new Document();
        sum.put("$sum",1);
        Document id_count = new Document();
        id_count.put("_id",null);
        id_count.put("count",sum);
        Document group = new Document();
        group.put("$group",id_count);
        ArrayList<Document> lists = new ArrayList<>();
        lists.add(group);
        AggregateIterable aggregate = collection.aggregate(lists);
        MongoCursor<Document> iterator8 = aggregate.iterator();
        while (iterator8.hasNext()) {
            Document next = iterator8.next();
            Integer count = next.getInteger("count");
            System.out.println("count = " + count);
        }
        //查询集合中文档中size的值得总和  aggregate([{$group:{_id:null,totalSize:{$sum:"$size"}}}])
        //若是需要查看分组title中得size值得总和, aggregate([{$group:{_id:"$title",totalSize:{$sum:"$size"}}}])
        Document sum1 = new Document();
        sum.put("$sum","$size");
        Document id_totalSize = new Document();
        id_totalSize.put("_id",null);
        //id_totalSize.put("_id","$title");
        id_totalSize.put("totalSize",sum);
        Document group1 = new Document();
        group1.put("$group",id_totalSize);
        ArrayList<Document> lists1 = new ArrayList<>();
        lists1.add(group);
        AggregateIterable aggregate1 = collection.aggregate(lists1);
        MongoCursor<Document> iterator10 = aggregate1.iterator();
        while (iterator10.hasNext()) {
            Document next = iterator10.next();
            Integer totalSize = next.getInteger("totalSize");
            System.out.println("totalSize = " + totalSize);
        }

        //聚合操作,分组前得数据过滤 :  -$match
        //查看dev集合中有多少文档得size大于200   下面分为两部分,第一部分条件过滤,第二部分是查看总数
        //aggregate([{$match:{size:{$gt:200}}},{$group:{_id:null,totalSize:{$sum:1}}}])
        Document sums = new Document();
        sums.put("$sum",1);
        Document id_totalSizes = new Document();
        id_totalSizes.put("_id",null);
        id_totalSizes.put("totalSize",sums);
        Document groups = new Document();
        groups.put("$group",id_totalSizes);
        Document gt = new Document();
        gt.put("$gt",200);
        Document sizes = new Document();
        sizes.put("size",gt);
        Document match = new Document();
        match.put("$match",sizes);
        ArrayList<Document> documents = new ArrayList<>();
        documents.add(groups);
        documents.add(match);
        AggregateIterable<Document> iterator11 = collection.aggregate(documents);
        MongoCursor<Document> iterator12 = iterator11.iterator();
        while (iterator12.hasNext()) {
            Document next = iterator12.next();
            Integer totalSize = next.getInteger("totalSize");
            System.out.println("totalSize = " + totalSize);
        }

        //聚合操作,分组后得数据过滤
        //查询dev集合,根据title分组计算出每组得size总和,并过滤掉总和小于200得文档
        //db.dev.aggregate([{$group:{_id:"$title",totalSize:{$sum:"$size"},{$smatch:{totalSize:{$lt:200}}}])

    }
在这里插入代码片
/**
 * @date 2022年02月24日 11:01
 * 连接MongoDB - 使用连接池 - 使用用户认证
 */
public class MongoDBAuthPoolUtil {
    private static MongoClient client = null;

    static {
        if (client == null) {
            //创建MongoDB连接池
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //设置每个地址的最大连接数,默认是10
            builder.connectionsPerHost(10);
            //设置超时时间,毫秒
            builder.connectTimeout(5000);
            //设置读写超时时间,毫秒
            builder.socketTimeout(5000);
            //创建一个封装用户认证信息
            MongoCredential credential = MongoCredential.createCredential("用户名","数据库名称","用户密码".toCharArray());
            ServerAddress address = new ServerAddress("localhost", 27017);
            client = new MongoClient(address,credential,builder.build());
            //如果是集群可以用下面这个
            //client = new MongoClient(Arrays.asList(address),credential,builder.build());
        }
    }

    //获取MongoDB数据库
    public static MongoDatabase getDatabase(String dbName) {
        return client.getDatabase(dbName);
    }

    //获取MongoDB中的集合
    public static MongoCollection getCollection(String dbName, String  collName){
        MongoDatabase database = getDatabase(dbName);
        MongoCollection collection = database.getCollection(collName);
        return collection;
    }

    //删除MongoDB中的集合
    public static void dropCollection(MongoCollection collection){
        collection.drop();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值