• 数据库.MongoDB.Java样例


    1.先在MongoDB官网下载Java驱动包

    MongoDB Java Driver:

    http://mongodb.github.io/mongo-java-driver/

    JAR包下载列表

    https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.5.0/

    2.程序样例

     1 package com.test;
     2 
     3 import java.util.Arrays;
     4 
     5 import org.bson.Document;
     6 
     7 import com.mongodb.MongoClient;
     8 import com.mongodb.client.MongoCollection;
     9 import com.mongodb.client.MongoDatabase;
    10 
    11 public class MongoDb_Test2 {
    12     public static void main(String[] args) {  
    13         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    14         MongoDatabase database = mongoClient.getDatabase("mydb");
    15         MongoCollection<Document> collection = database.getCollection("test");
    16         System.out.println(collection.count());
    17         Document doc = new Document("name", "MongoDB")
    18         .append("type", "database")
    19         .append("count", 1)
    20         .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
    21         .append("info", new Document("x", 203).append("y", 102));
    22         collection.insertOne(doc);
    23         System.out.println(collection.count());
    24         System.out.println("done!");
    25     }
    26 }

    执行结果:

    读取数据样例

            FindIterable<Document> iterable = collection.find().limit(1);
            MongoCursor<Document> cursor = iterable.iterator();
            if(cursor.hasNext()) {
                Document user = (Document)cursor.next();
                System.out.println(user.get("name"));
                System.out.println(user.toString());
            }
            cursor.close();
  • 相关阅读:
    Cx的治疗
    [HDU2222] Keywords Search
    楼房
    [51Nod1089] 最长回文子串 V2(Manacher算法)
    [洛谷P3375] 【模板】KMP字符串匹配
    [codeVS1204] 寻找子串位置
    [洛谷P1114] “非常男女”计划
    [BZOJ2132] 圈地计划
    [COGS311] Redundant Paths
    [COGS309] [USACO 3.2] 香甜的黄油
  • 原文地址:https://www.cnblogs.com/visionsl/p/7644606.html
Copyright © 2020-2023  润新知