Learning mongodb--(11): Application examples (using Java to manipulate MongoDB)

Source: Internet
Author: User
Tags findone mongodb collection mongodb server

Original address: http://blog.csdn.net/drifterj/article/details/7948090

Directory Address: HTTP://BLOG.CSDN.NET/DRIFTERJ/ARTICLE/CATEGORY/1191327/2

In the front we all manipulate the data accessing MongoDB through the shell, the language used in the shell is JavaScript. Let's talk about how to access the MongoDB database through Java.

The Java driver is the earliest driver of MongoDB and has been used in the production environment for a long time and is very stable. Can be downloaded to the official MongoDB website driver, my resources are also, the driver version is 2.9.0.

In this jar file, there are two packages, and we will often use Com.mongodb and Com.mongodb.gridfs. Working with MongoDB in Java, the concepts are similar to those in the shell, and almost all of the method names are consistent, so let's look at a simple example:

[Java]View Plaincopy
  1. Package cn.test;
  2. Import java.net.UnknownHostException;
  3. Import Com.mongodb.BasicDBObject;
  4. Import Com.mongodb.DB;
  5. Import com.mongodb.DBCollection;
  6. Import Com.mongodb.DBObject;
  7. Import Com.mongodb.Mongo;
  8. Public class Test {
  9. public static void Main (string[] args) throws unknownhostexception {
  10. /** 
  11. * The MONGO class represents a connection to a MongoDB server and has several constructors. The parameterless constructor is the default connection localhost:27017.
  12. */
  13. Mongo connection = new Mongo ("localhost:20000");
  14. /** 
  15. * The DB class represents the database and, if the database is not present on the current server, creates a default
  16. */
  17. DB db = Connection.getdb ("mylearndb");
  18. /** 
  19. * Dbcollection represents the collection, and if the collection is not in the database, a default is created
  20. */
  21. Dbcollection users = db.getcollection ("users");
  22. /** 
  23. * DBObject represents the document, this is an interface, Java provides a variety of implementations, the simplest is basicdbobject
  24. */
  25. DBObject user = new Basicdbobject ();
  26. User.put ("name", "Jimmy");
  27. User.put ("age", "34");
  28. DBObject address = new Basicdbobject ();
  29. Address.put ("City", "BJ");
  30. Address.put ("Street", "Bq Road");
  31. Address.put ("Mail", "Ufpark 68#");
  32. /** 
  33. * For inline documents, we need to populate the embedded documents before populating the outer documents!
  34. */
  35. User.put ("address", address);
  36. //Insert the document into the collection
  37. Users.insert (user);
  38. //Query the data from the collection, we query one, call FindOne can
  39. DBObject DbUser = Users.findone ();
  40. System.out.println ("name" + ":" + dbuser.get ("name"));
  41. System.out.println ("Age" + ":" + dbuser.get ("age"));
  42. DBObject dbaddress = (dbobject) user.get ("address");
  43. System.out.println ("City" + ":" + dbaddress.get ("City"));
  44. System.out.println ("Street" + ":" + dbaddress.get ("Street"));
  45. System.out.println ("Mail" + ":" + dbaddress.get ("Mail"));
  46. }
  47. }


The output is:

[Java]View Plaincopy
    1. Name:jimmy
    2. Age:
    3. City:bj
    4. STREET:BQ Road
    5. Mail:ufpark 68#

From the above example, we can see that the use of Java-driven operation of MongoDB and the shell is very similar to the operation, Java operations more OO features.

Let's mention here a little bit about the document class explained in the above comment. The Java driver Chinese file must be a DBObject interface type, which can be considered an orderly java.util.Map. There are many implementations available in the Java driver, and the simplest basicdbobject are used in our example.

"Saving an array to a collection"

The values of the key-value pairs in the MongoDB collection support arrays, and in the shell we use [] to represent arrays, and how do the Java drivers represent arrays? In the Java driver, an object of type Java.util.List can represent an array in MongoDB! Let's look at an example:

[Java]View Plaincopy
  1. Package cn.test;
  2. Import java.net.UnknownHostException;
  3. Import java.util.ArrayList;
  4. Import java.util.List;
  5. Import Com.mongodb.BasicDBObject;
  6. Import Com.mongodb.BasicDBObjectBuilder;
  7. Import Com.mongodb.DB;
  8. Import com.mongodb.DBCollection;
  9. Import Com.mongodb.DBObject;
  10. Import Com.mongodb.Mongo;
  11. Public class Test1 {
  12. public static void Main (string[] args) throws unknownhostexception {
  13. /** 
  14. * The MONGO class represents a connection to a MongoDB server and has several constructors. The parameterless constructor is the default connection localhost:27017.
  15. */
  16. Mongo connection = new Mongo ("localhost:20000");
  17. /** 
  18. * The DB class represents the database and, if the database is not present on the current server, creates a default
  19. */
  20. DB db = Connection.getdb ("mylearndb");
  21. /** 
  22. * Dbcollection represents the collection, and if the collection is not in the database, a default is created
  23. */
  24. Dbcollection fruitshop = db.getcollection ("Fruitshop");
  25. /** 
  26. * Create a fruit Shop Document object
  27. */
  28. DBObject SHOP1 = new Basicdbobject ();
  29. Shop1.put ("name", "the Fruit King");
  30. /** 
  31. * Fruit store fruit stored in an array of inline documents in the format:
  32. * [{"name": "Apple", "quality": "Good", "price": "5.6"},
  33. * {"name": "Orange", "quality": "Normal", "price": "1.5"},
  34. *   ......]
  35. */
  36. //array represented by list
  37. list<dbobject> fruits = new arraylist<dbobject> ();
  38. //Each document in the array, we construct it by Basicdbobjectbuilder
  39. Fruits.add (Basicdbobjectbuilder.start (). Add ("name", "Apple"). Add ("quality", "good"). Add ("  Price ", " 5.6 "). get ());
  40. Fruits.add (Basicdbobjectbuilder.start (). Add ("name", "Orange"). Add ("quality", "normal"). Add (  "Price", "1.5"). get ());
  41. Shop1.put ("fruits", fruits);
  42. Fruitshop.insert (SHOP1);
  43. }
  44. }


We connect to the database through the shell and visually look at the data in the collection in the database:

[JavaScript]View Plaincopy
  1. > Use mylearndb;
  2. Switched to DB mylearndb
  3. > Db.fruitshop.find ();
  4. { "_id": ObjectId ("504c26fed9005e6e410c5979"), "name": "the Fruit King", "Frui
  5. TS": [{" Name":" Apple"," Quality":" Good"," Price " /c4>
  6. : "5.6"}, { "name": "Orange", "quality": "normal", "price"
  7. : "1.5"}]}
  8. >


The above is a simple example of using the Java driver to manipulate MongoDB, using Java driver to operate MongoDB is very simple, we actually use in the API can refer to the official documentation provided by MongoDB.

The following link is the API documentation for version 2.9.0 Driver:

http://api.mongodb.org/java/2.9.0/

Learning mongodb--(11): Application examples (using Java to manipulate MongoDB)

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.