0

这是我第一次尝试使用 MongoDB java 驱动程序,所以我只是在尝试示例。我已将驱动程序 jar 添加到库中,并且所有导入工作正常。但是,每当我尝试写其他东西时,就像MongoClient mongoClient = new MongoClient();我得到错误一样Syntax error on tokens, delete these tokens。事实上,它不仅仅是特定于 mongo 的。写任何东西都会产生这个错误。

如果答案真的很明显,我深表歉意:/

4

1 回答 1

0

尝试将语句放在类中,如下所示:

    import com.mongodb.MongoClient;
    import com.mongodb.MongoException;
    import com.mongodb.WriteConcern;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import com.mongodb.DBCursor;
    import com.mongodb.ServerAddress;

    import java.util.Arrays;

    public Class MongoSample{

    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    // if it's a member of a replica set:
    MongoClient mongoClient = new MongoClient();
    // or
    MongoClient mongoClient = new MongoClient( "localhost" );
    // or
    MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
    MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                          new ServerAddress("localhost", 27018),
                                          new ServerAddress("localhost", 27019)));

    DB db = mongoClient.getDB( "mydb" );
}

请在发布之前尝试在 google/stackoverflow 上调查该问题。你会学到很多东西,并且能够帮助别人。

我从这个答案中发现了可能的问题

于 2013-10-06T04:02:37.657 回答