1. 程式人生 > >MongoDB java版 增刪改查

MongoDB java版 增刪改查

private  static  MongoCollection<Document>   getMongoCollection(){
        MongoClient mongoClient = new MongoClient("192.168.5.233", 27022);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("test4");
        MongoCollection<Document> documentMongoCollection = mongoDatabase.getCollection("user");
        return documentMongoCollection;
    }


    /***
     *  查詢
     */
    private static void find() {
        Filters.regex("user",".*s.*");  // like %s%
        FindIterable<Document> findIterable = getMongoCollection().find();
        Block<Document> printDoc = new Block<Document>() {
            @Override
            public void apply(Document document) {
                System.out.println(document.toJson());
            }
        };
        findIterable.forEach(printDoc);
    }


    /**
     *  刪除
     */

    private static void delete() {
        DeleteResult deleteResult= getMongoCollection().deleteMany(Filters.eq("name","zhangsan"));

        System.out.println(deleteResult.getDeletedCount()+"");


        //刪除大於8 小於10 的年紀資料

        DeleteResult deleteR= getMongoCollection().deleteMany(Filters.and(Filters.gt("age",8),Filters.lt("age",10)));


        System.out.println(deleteR.getDeletedCount()+"");

    }


    /**
     *   更新
     */

    private static void update() {


        UpdateResult  updateResult= getMongoCollection().updateMany(Filters.eq("name","tes2"),new Document("$set",new Document("age",10)));
        System.out.println(updateResult.getModifiedCount()+"");


    }


    /**
     *  增加
     */

    private static void add() {
        List<Document> doc1 = new ArrayList<>();
        Document document1 = new Document();
        document1.put("name", "zhangsan");
        document1.put("age", 1);
        document1.put("price", 1.77f);
        doc1.add(document1);
        List<Document> doc2 = new ArrayList<>();

        Document document2 = new Document();
        document2.put("name", "tes2");
        document2.put("age", 4);
        document2.put("price", 2.77f);
        doc1.add(document2);
        getMongoCollection().insertMany(doc1);
    }