当前位置: 首页>>代码示例>>Java>>正文


Java MongoClient类代码示例

本文整理汇总了Java中com.mongodb.MongoClient的典型用法代码示例。如果您正苦于以下问题:Java MongoClient类的具体用法?Java MongoClient怎么用?Java MongoClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MongoClient类属于com.mongodb包,在下文中一共展示了MongoClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getCodecRegistry

import com.mongodb.MongoClient; //导入依赖的package包/类
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(CodecResolverTest.class)
                            .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
                                if (TypeUtils.isAssignable(type, Base.class)) {
                                    return new DocumentCodec((Class<? extends Base>) type, typeCodecRegistry, codecConfiguration);
                                }
                                return null;
                            })
                            .build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:18,代码来源:CodecResolverTest.java

示例2: failedInputOfComment

import com.mongodb.MongoClient; //导入依赖的package包/类
@Test
public void failedInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd27\", comment : \"Here is our comment for this test\" }";

    assertFalse(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    FindIterable findIterable = plants.find();
    Iterator iterator = findIterable.iterator();
    while(iterator.hasNext()){
        Document plant = (Document) iterator.next();
        List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
        assertEquals(0,plantComments.size());
    }
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:19,代码来源:TestPlantComment.java

示例3: connectToDatabaseCluster

import com.mongodb.MongoClient; //导入依赖的package包/类
public boolean connectToDatabaseCluster(final List<String> seeds) {
    try {
        List<ServerAddress> seedList = new ArrayList<>();
        for (String ip : seeds) {
            seedList.add(new ServerAddress(ip, MONGO_PORT));
        }
        mongoClient = new MongoClient(seedList);
        mongoDatabase = mongoClient.getDatabase("featureStore");
        dbCollectionList = getCollectionList(mongoDatabase);
        log.info("Connect to database cluster successfully!!");

        return true;
    } catch (Exception e) {
        log.warn(e.getMessage());
        return false;
    }
}
 
开发者ID:shlee89,项目名称:athena,代码行数:18,代码来源:FeatureDatabaseMgmtManager.java

示例4: main

import com.mongodb.MongoClient; //导入依赖的package包/类
public static void main(String[] args) {
    MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build();
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions);

    MongoDatabase database = mongoClient.getDatabase("tutorial");
    MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class);

    // create some pojo
    Pojo pojo = new Pojo();
    pojo.setName("A nice name");
    pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48)));

    // insert into db
    collection.insertOne(pojo);

    // read from db
    PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first();

    // output
    LOGGER.debug("Found pojo {}", foundPojo);
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:22,代码来源:Tutorial.java

示例5: BingoChessChallenge

import com.mongodb.MongoClient; //导入依赖的package包/类
public BingoChessChallenge(String[] args) {
	announcer = new Chatter(args[0]);
	lichs = new HashMap<String,Lichesser>();
	chessplayers = new HashMap<String,ChessPlayer>();
	chessgames = new HashMap<String,LichessGame>();
	BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
	for (int x=0;x<8;x++)
	for (int y=0;y<8;y++)
	BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
	initIRC(args[0], args[1], args[2], args[3]);
	loadAdmins("res/admins.txt");
	serv = new BingoServ(Integer.parseInt(args[4]),this);
	serv.startSrv();
	bingoURL = args[5];
	MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
	MongoClient mongoClient = new MongoClient(connStr);
	MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase");
	playData = bingoBase.getCollection("players");
}
 
开发者ID:JohnChernoff,项目名称:BingoChess,代码行数:20,代码来源:BingoChessChallenge.java

示例6: successfulInputOfComment

import com.mongodb.MongoClient; //导入依赖的package包/类
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

    Iterator<Document> iter = plants.find(filterDoc).iterator();

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:26,代码来源:TestPlantComment.java

示例7: setup

import com.mongodb.MongoClient; //导入依赖的package包/类
private static void setup() throws UnknownHostException, IOException {
  IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().verbose(false)
      .enableAuth(authEnabled).build();

  IMongodConfig mongodConfig = new MongodConfigBuilder()
      .version(Version.Main.PRODUCTION)
      .net(new Net(LOCALHOST, MONGOS_PORT, Network.localhostIsIPv6()))
      .cmdOptions(cmdOptions).build();

  IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(
      Command.MongoD).build();
  mongodExecutable = MongodStarter.getInstance(runtimeConfig).prepare(
      mongodConfig);
  mongod = mongodExecutable.start();
  mongoClient = new MongoClient(new ServerAddress(LOCALHOST, MONGOS_PORT));
  createDbAndCollections(EMPLOYEE_DB, EMPINFO_COLLECTION, "employee_id");
  createDbAndCollections(EMPLOYEE_DB, SCHEMA_CHANGE_COLLECTION, "field_2");
}
 
开发者ID:skhalifa,项目名称:QDrill,代码行数:19,代码来源:MongoTestSuit.java

示例8: testMongo1

import com.mongodb.MongoClient; //导入依赖的package包/类
@POST
@Path("testMongo1")
public void testMongo1(String jsonString) {

    MongoClient client = new MongoClient();
    client.listDatabaseNames().first();
    MongoDatabase db = client.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    MongoCollection<Document> collection = db.getCollection("test");
    collection.listIndexes().first();
    Document doc = new Document("name", "Amarcord Pizzeria")
            .append("contact",
                    new Document("phone", "264-555-0193").append("email", "[email protected]")
                            .append("location", Arrays.asList(-73.88502, 40.749556)))
            .append("stars", 2).append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
    collection.insertOne(doc);
    collection.find().first();

    MongoClient client2 = new MongoClient("localhost:27017");
    db = client2.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    collection = db.getCollection("test");
    collection.listIndexes().first();

    client.close();
    client2.close();
}
 
开发者ID:uavorg,项目名称:uavstack,代码行数:28,代码来源:TestRestService.java

示例9: getCodecRegistry

import com.mongodb.MongoClient; //导入依赖的package包/类
@Bean()
public static CodecRegistry getCodecRegistry() {
    return CodecRegistries.fromRegistries(
            CodecRegistries.fromProviders(
                    new EnumCodecProvider(),
                    PojoCodecProvider.builder()
                            .register(Pojo.class.getPackage().getName())
                            .registerCodecResolver((CodecResolver) (type, typeCodecRegistry, codecConfiguration) -> {
                                if (TypeUtils.isAssignable(type, CustomId.class)) {
                                    return new CustomIdCodec((Class<CustomId>)type, typeCodecRegistry, codecConfiguration);
                                }
                                return null;
                            }).build()
            ),
            MongoClient.getDefaultCodecRegistry());
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:17,代码来源:ExternalIdCodecProviderTest.java

示例10: ensureIndexes

import com.mongodb.MongoClient; //导入依赖的package包/类
public static <T extends OkraItem> void ensureIndexes(final Okra<T> okra,
                                                      final MongoClient mongo,
                                                      final String database,
                                                      final String collection) {
    okra.getIndexDefs()
            .stream()
            .map(indexDef -> {
                final boolean ascending = indexDef.getOrdering() == null
                        || indexDef.getOrdering().equals(Ordering.ASC);

                final Bson ordering = ascending
                        ? Indexes.ascending(indexDef.getAttrs()) : Indexes.descending(indexDef.getAttrs());

                return mongo
                        .getDatabase(database)
                        .getCollection(collection)
                        .createIndex(ordering);
            })
            .forEach(indexName -> LOGGER.info("Done. Index name: {}", indexName));
}
 
开发者ID:OkraScheduler,项目名称:OkraSync,代码行数:21,代码来源:IndexCreator.java

示例11: Connect

import com.mongodb.MongoClient; //导入依赖的package包/类
public void Connect(String user, String pass) {
	try {
		logger.info("Connecting to " + connectionString);

		// Authaenticate
		// MongoCredential credential =
		// MongoCredential.createCredential(user,
		// "admin",
		// pass); //Only users on admin as that will be mandatory in 3.6

		mongoClient = new MongoClient(new MongoClientURI(connectionString));

		mongoClient.getDatabase("admin")
				.runCommand(new Document("ping", 1));

	} catch (Exception e) {
		logger.error("Unable to connect to MongoDB");
		logger.error(e.getMessage());
		System.exit(1);
	}
	this.user = user;
	this.pass = pass;
}
 
开发者ID:johnlpage,项目名称:MongoSyphon,代码行数:24,代码来源:MongoConnection.java

示例12: AddFlowerRatingReturnsTrueWithValidJsonInput

import com.mongodb.MongoClient; //导入依赖的package包/类
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-3-sixguysburgers-fries,代码行数:23,代码来源:FlowerRating.java

示例13: test_mongoservice_not_enabled

import com.mongodb.MongoClient; //导入依赖的package包/类
@Test
public void test_mongoservice_not_enabled() throws InitializationException {
    final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
    final StandardMongoClientService service = new StandardMongoClientService();

    runner.addControllerService("test-mongo-closed", service);
    runner.enableControllerService(service);

    // Close MongoClient
    MongoClient client = service.getMongoClient();

    // NOTE: This test requires mongo to be running
    assertEquals("localhost:27017", client.getConnectPoint());

    // Close the mongo connection
    client.close();

    // Now, this should throw an illegal state exception
    thrown.expect(IllegalStateException.class);
    client.getConnectPoint();
}
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:22,代码来源:StandardMongoClientServiceIT.java

示例14: testUpsertTrue

import com.mongodb.MongoClient; //导入依赖的package包/类
@Test
public void testUpsertTrue() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "upsert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.g");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$unset");
    runner.setProperty(MongoProps.UPSERT, "true");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify that document wasn't inserted
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("upsert_test");
        assertEquals(1, collection.count());
    }
}
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:28,代码来源:UpdateMongoIT.java

示例15: configure

import com.mongodb.MongoClient; //导入依赖的package包/类
@BeforeTest
private void configure() {
    final String mongoURI = System.getProperty("indra.mongoURI");
    if (mongoURI == null) {
        Assert.fail("System.getProperty(\"indra.mongoURI\") is null. Provide a mongoURI to execute the integration test.");
    }

    MongoClientOptions builder = MongoClientOptions.builder().serverSelectionTimeout(5000).build();
    MongoClient mongoClient = new MongoClient(mongoURI, builder);
    vectorSpaceFactory = new MongoVectorSpaceFactory(mongoClient);
    translatorFactory = new MongoTranslatorFactory(mongoClient);
}
 
开发者ID:Lambda-3,项目名称:Indra,代码行数:13,代码来源:MongoIndraDriverIT.java


注:本文中的com.mongodb.MongoClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。