MongoDB Java access

Source: Internet
Author: User
Tags findone testng

MongoDB Java drivers have provided comprehensive operations, divided into three parts:

1. Common user operations

2. Administrator operations

3. oplog operations

You can add an eclipse testng plug-in and import the testng. jar package to the project.

This article describes the usage and precautions.


1. Connect a replica set (replica sets) into D:

The replica set is a mongo solution for stability and can implement read/write splitting. Here we introduce the java connection method of the replica set.

[Java]

  1. StaticMongo m;
  2. Static{
  3. List <ServerAddress> addresslist =NewArrayList <ServerAddress> ();
  4. Try{
  5. Addresslist. add (NewServerAddress ("Fig: 10240"));
  6. Addresslist. add (NewServerAddress ("Fig: 11240"));
  7. Addresslist. add (NewServerAddress ("Fig: 12240"));
  8. }Catch(UnknownHostException e ){
  9. System. err. println ("Address check error .");
  10. System. exit (-1);
  11. }
  12. Optional options =NewUsing options ();
  13. Options. autoConnectRetry =True;
  14. Options. connectionsPerHost =20;
  15. Options. connectTimeout =6000;
  16. Options. maxAutoConnectRetryTime =12000;
  17. Options. maxWaitTime =12000;
  18. Options. socketKeepAlive =True;
  19. Options. socketTimeout =2000;
  20. Try{
  21. M =NewMongo (addresslist, options );
  22. }Catch(Except exception e ){
  23. System. err. println ("Mongo create error .");
  24. System. exit (-1);
  25. }
  26. }
Note: The connection method used in the general example is to directly connect to a mongod service, but as a single production environment, the security is obviously insufficient. Therefore, the replica set method is used, and the connection is different from the general method.

[Java]

  1. PublicMongo (List <ServerAddress> replicaSetSeeds, using options)ThrowsExcept exception
Method.

When options is set according to your needs, there are already many parameter descriptions.

Note that mongo instances use Singleton mode.


2. Obtain the database:

[Java]

  1. DB db = m. getDB ("Test");
Note: Obtain the database named test for the operation. If the database does not exist, the Operation will create the corresponding database.


3. Get the set:

[Java]

  1. DBCollection col = db. getCollection ("Offer");

Note: This is a set named offer. It is similar to a db table.


The above three operations are to establish a connection, followed by common operations in db.


4. Query:

[Java]

  1. DBCursor cursor = col. find ();
  2. While(Cursor. hasNext ()){
  3. System. out. println (cursor. next ());
  4. I ++;
  5. }
Note: The full-set query outputs each record. Normally, similar operations are not performed. remember two things: find () and cursor.


[Java]

  1. BasicDBObject query =NewBasicDBObject ();
  2. Query =NewBasicDBObject ();
  3. Query. put ("I",NewBasicDBObject ("$ Gt",20). Append ("$ Lte",30));// I. e. 20 <I <= 30
  4. <Pre name ="Code" Class="Java"> DBCursor cur = coll. find (query );
  5. While(Cur. hasNext ()){
  6. System. out. println (cur. next ());
  7. }

Note: query the offer information of a specified condition. 


[Java]

  1. DBObject tmpdoc = col. findOne (doc );
Note: query a single record. When it is clear that one record has only one record, findOne () is more convenient to avoid the trouble of moving the cursor.


5. Update:

[Java]

  1. DBObject tmpdoc = col. findOne (doc );
  2. Tmpdoc. put ("I", (Integer) tmpdoc. get ("I") +1);
  3. System. out. println ("Update obj :"+ Col. findOne (tmpdoc ));
Note: to update a record, read the entire record and then update some information before writing it, Do not read some updates back.


6. insert:

[Java]

  1. IntI =1000;
  2. BasicDBObject doc =NewBasicDBObject ();
  3. Doc. put ("I", I +1);
  4. Col. insert (doc );
  5. System. out. println ("Insert obj :"+ Col. findOne (doc ));
Note: Insert a record {I: 1001}, _ id is automatically generated.


7. Delete:

[Java]

  1. BasicDBObject doc =NewBasicDBObject ();
  2. Doc. put ("I", I +1);
  3. Col. remove (doc );
  4. System. out. println ("Insert obj :"+ Col. findOne (doc ));
Note: delete a record.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.