技术开发 频道

Java Tutorial:Java操作MongoDB入门

  Authentication (Optional)

  授权(可选)

  MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with the connected mongo object :

  MongoDB可以运行在通过用户名和密码控制的安全的模式下。当以安全模式运行时,任何客户端应用程序的操作必须验证用户名和密码。在java中,验证很简单:

boolean auth = db.authenticate(myUserName, myPassword);

  If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.

  如果用户名和密码正确,auth值为true。错误为false。在日志中可以看到更多有效的信息。

  Most users run MongoDB without authentication in a trusted environment.

  很多用户将MongoDB以非授权模式运行在安全的环境中。

  Getting A List Of Collections

  查询Collection的集合(Collection类似于表)

  Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :

  每个数据库可以有任意个collection。通过db对象可以检索并打印出来:

Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}

  and assuming that there are two collections, name and address, in the database, you would see

  假如数据库中有name和address两个collection,结果输出入下:

name

address

  as the output.

  Getting A Collection

  得到Collection

  To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:

  要使用collection,使用getCollection(String collectionName) 方法传入collection的名称:

DBCollection coll = db.getCollection("testCollection")

  Once you have this collection object, you can now do things like insert data, query for data, etc

  得到collection对象后就可以进行插入、查询等操作了。

0
相关文章