首页 > 解决方案 > 为什么我得到一个错误找不到符号,符号:类 Mongoclient?

问题描述

我正在尝试在现有数据库中创建新集合。

try {
        
     MongoCollection collection = null;
     MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
     MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "udata");
     collection = mongoTemplate.createCollection("MyNewCollection");
     }
     catch (Exception e) {
            e.printStackTrace();
         }

我正在使用 spring boot 并导入以下包:

import com.mongodb.client.MongoClients;

import com.oegems.ems.EmsMongoOps;

import com.mongodb.client.MongoCollection ;

这是我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.oegems</groupId>
    <artifactId>ems</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ems</name>
    <description>Demo project for ..</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

标签: mongodbspring-bootmongotemplate

解决方案


您的导入包含以下内容:

import com.mongodb.client.MongoClients;

这是一个有效的类,一个MongoClient实例工厂

最后注意额外s

然后,您使用:

MongoClient mongoClient

请注意,编译器MongoCollection已从上面的行中识别出与MongoClient

所以使用一个而不是另一个:

import com.mongodb.client.MongoClient;

import com.mongodb.client.MongoClients;


推荐阅读