1. Download the mongoDB jar package and import it into the CLASSPATH of the project
2. Link to the mongoDB server and select the database
To establish a MongoDB connection, you simply specify the database you want to connect to. This database does not necessarily exist. If it does not exist, MongoDB will first create this database for you. At the same time, you can also specify the network address and port to connect to when connecting:
Mongo m = new Mongo(); // or Mongo m = new Mongo( “localhost” ); // or Mongo m = new Mongo( “localhost”, 27017 ); // or, to connect to a replica set, supply a seed list of members Mongo m = new Mongo(Arrays.asList(new ServerAddress(“localhost”, 27017), New ServerAddress(“localhost”, 27018), New ServerAddress(“localhost”, 27019))); DB db = m.getDB( “mydb” ); |
3. Security verification (optional)
boolean auth = db.authenticate(userName, password); |
4. Get the collection list. Each database has zero or more collections, and you can get a list of them when needed:
Set colls = db. getCollectionNames();
for (String s : colls) { System. out. println(s); }
5. Get a set. To get a specific collection, you can specify the name of the collection and use the getCollection() method:
DBCollection coll = db.getCollection(“blog”);
6. Insert document
mongodb stores documents in JSON format, and the easiest class to represent this data format in Java is Map. MongoDB Java
The BasicDBObject provided in the Driver is a Map (it inherits from LinkedHashMap and implements the DBObject interface), which converts the data in the Map into BSON format and transmits it to mongodb.
BasicDBObject doc = new BasicDBObject();
doc.put(“name”, “MongoDB”); doc.put(“type”, “database”);
doc.put(“count”, 1); BasicDBObject info = new BasicDBObject();
info. put(“x”, 203); info. put(“y”, 102); doc. put(“info”, info);
coll.insert(doc);
Each inserted document in mongodb will generate a unique identifier _id. When calling coll.insert(doc);, the driver will check whether there is an _id field, and if not, it will automatically generate an ObjectId instance as the value of _id. This ObjectId is encoded by 4 parts: current time, machine ID, Process ID and auto-incrementing integer. The insert function also supports inserting document lists: insert(List
list)
7. Query The find function is used to query collections, and the DBCursor it returns is an iterator of DBObject. The following code:
BasicDBObject query = new BasicDBObject(); query. put(“i”, 71);
cursor = coll. find(query); try { while(cursor. hasNext()) {
System.out.println(cursor.next()); } } finally { cursor.close();
}
8. Build an index
Create an index statement such as: coll.createIndex(new BasicDBObject(“i”, 1));
, where i represents the field to be indexed, 1 for ascending order (-1 for descending order). It can be seen that DBObject has become a common structural representation of java clients. To view the index use the DBCollection.getIndexInfo() function.