MongoDB Java Driver Simple operation
One, Java driver consistency
MongoDB Java driver is thread-safe, for general applications, as long as a MONGO instance can be, MONGO has a built-in connection pool (pool size defaults to 10).
For environments with a large number of writes and reads, to ensure that the same db is used in a session, we can guarantee consistency in the following ways:
DB mdb = mongo.getdb (' dbname ');
Mdb.requeststart ();
//
Business code
//
Mdb.requestdone ();
DB and Dbcollection are absolutely thread-safe, they are cached, so it is possible that the same object is taken in the application.
Second, save/Find Object (DBObject)
The Java driver provides a dbobject interface that allows us to save objects to the database.
Define the objects you want to save:
public class Tweet implements DBObject {
/** ...... */
}
Then we can use the object:
Tweet tweet = new tweet ();
Tweet.put ("User", userId);
Tweet.put ("message", message);
Tweet.put ("Date", new Date ());
Collection.insert (tweet);
When querying from a database, the results are automatically converted into DBObject objects, which we can convert to our own type:
Collection.setobjectclass (Tweet);
Tweet Mytweet = (tweet) collection.findone ();
Third, create the connection
Mongo m = new Mongo ();
Mongo m = new Mongo ("localhost");
Mongo m = new Mongo ("localhost", 27017);
DB db = M.getdb ("MyDB");
Note: In fact, the MONGO instance represents a database connection pool, and even in a multithreaded environment, a MONGO instance is sufficient for us.
IV. Certification (optional)
Boolean auth = db.authenticate ("MyUserName", "mypasswd");
V. Get a list of collection
Set<string> colls = Db.getcollectionnames ();
for (String s:colls) {
SYSTEM.OUT.PRINLN (s);
}
Six, get a collection
Dbcollection coll = db.getcollection ("testcollection");
Using Dbcollection, we can perform data manipulation such as inserting and querying data.
Vii. Inserting documents
Suppose you have a JSON document that looks like this:
{
"Name": "MongoDB",
"Type": "Database",
"Count": 1,
"Info": {
x:203,
y:102
}
}
Note: The JSON document above has an inline document "info".
We can use Basicdbobject to create a document like the JSON above and save it in MongoDB.
DBObject doc = new Basicdbobject ();
Doc.put ("name", "MongoDB");
Doc.put ("type", "database");
Doc.put ("Count", 1);
DBObject info = new Basicdbobject ();
Info.put ("x", 203);
Info.put ("Y", 102);
Doc.put ("info", info);
Coll.insert (DOC);
Viii. querying the first document (FindOne ())
To verify the JSON-like data we saved above, we can use the FindOne () method to get the data.
FindOne (): Returns a document;
Find (): Returns a cursor (dbcursor) that contains a set of object dbobject;
DBObject doc = Coll.findone ();
System.out.println (DOC);
We will see the console output:
{"_id": "49902cde5162504500b45c2c", "name": "MongoDB", "type": "Database", "Count": 1, "info": {"x": 203, "Y" : 102}, "_ns": "Testcollection"}
Nine, insert multiple documents
To show more query methods later, we first insert several documents, and their JSON looks like this:
{
"I": value
}
Insert data using a loop:
for (int i = 0; i <; i++) {
Coll.insert (New Basicdbobject (). Append ("I", I));
}
We note that the same Coll, we can completely insert different styles of data, which is the important feature of MongoDB "mode free".
X. Number of statistical documents
Now that we have 101 documents in the database, now count the numbers to see if they are correct.
Long Count = Coll.getcount ();
System.out.println (count);
The console will output: 101
Xi. using cursors to obtain all documents
dbcursor cursor = Coll.find ();
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (object);
}
12. Querying Individual documents
DBObject query = new Basicdbobject ();
Query.put ("I", 71);
cursor = coll.find (query);
while (Cur.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (object);
}
The output of the console is similar to the following:
{"_id": "49903677516250c1008d624e", "I": "_ns": "Testcollection"}
13. Query the collection of documents
Based on the query criteria, we can remove multiple objects from the database via dbcollection, such as querying I>50 's collection of documents:
query = new Basicdbobject ();
Query.put ("I", New Basicdbobject ("$gt", 50)); I>50
cursor = coll.find (query);
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (object);
}
For example, the query condition is 20<i<=30:
query = new Basicdbobject ();
20<i<=30
Query.put ("I", New Basicdbobject ("$gt"). Append ("$lte", 30));
cursor = coll.find (query);
while (Cursor.hasnext ()) {
DBObject object = Cursor.next ();
System.out.println (object);
}
14. Create an index
MongoDB supports indexing, and adding an index to a dbcollection is as simple as specifying the field to which you want to create an index, and then indicating whether it is ascending (1) or Descending (-1), such as creating an ascending index on "i".
Coll.createindex (New Basicdbobject ("I", 1)); 1 Stands for Ascending
Index of Query
We can query to all the indexes:
list<dbobject> list = Coll.getindexinfo ();
for (DBObject index:list) {
SYSTEM.OUT.PRINTLN (index);
}
The output of the console is similar to the following:
{"Name": "I_1", "ns": "Mydb.testcollection", "key": {"I": 1}, "_ns": "System.indexes"}
MongoDB's management function
First, get all the databases
Mongo m = new Mongo ();
For (String s:m.getdatabasenames ()) {
System.out.println (s);
}
Second, delete the database
M.dropdatabase ("my_new_db");
the Java type of MongoDB
First, Object ID
Objectid is used as the unique ID that is automatically generated.
ObjectId id = new ObjectId ();
ObjectId copy = new ObjectId (ID);
Second, the regular expression
Pattern John = Pattern.compile ("Joh?n", case_insensitive);
DBObject query = new Basicdbobject ("name", John);
Query All "name" documents that match/joh?n/i
dbcursor cursor = collection.find (query);
Third, date and time
Date now = new Date ();
DBObject time = new Basicdbobject ("TS", now);
Collection.save (time);
Iv. Database References
Dbref can be used to save database references.
Dbref addressref = new Dbref (db, "Foo.bar", address_id);
DBObject address = Addressref.fetch ();
DBObject person = Basicdbobjectbuilder.start ()
. Add ("Name", "Fred")
. Add ("Address", Addressref)
. get ();
Collection.save (person);
DBObject fred = Collection.findone ();
Dbref addressobj = (dbref) fred.get ("Address");
Addressobj.fetch ();
Five or two binary data
The byte array (byte[]) is treated as a binary data.
Vi. Embedded Documentation
The JSON-style data is as follows:
{
"X": {
"Y": 3
}
}
In MongoDB, Java is represented as:
DBObject y = new Basicdbobject ("Y", 3);
DBObject x = new Basicdbobject ("x", y);
Seven, array
Any object that inherits from the list, in MongoDB, is treated as an array.
If you want to represent the following JSON data:
{
"X": [
1,
2,
{"foo": "Bar"},
4
]
}
In Java, it should be:
list<object> x = new arraylist<object> ();
X.add (1);
X.add (2);
X.add (New Basicdbobject ("foo", "Bar"));
X.add (4);
DBObject doc = new Basicdbobject ("X", x);
System.out.println (DOC);
MongoDB Java Drive Use collation (GO)