Objective
MongoDB Java Driver provides the function of query, query condition is also Bson object, this article looks at how to carry on the simple data query
1. Data structure
Collection: Firstcollection
Data content:
{"_id": ObjectId ("55adba52fa1f3cf038c2aea6"), "name": "User0", "Age": $, "Sex": 0}
{"_id": ObjectId ("55adba52fa1f3cf038c2aea7"), "name": "User1", "age": All, "Sex": 1}
{"_id": ObjectId ("55adba52fa1f3cf038c2aea8"), "name": "User2", "Age": $, "Sex": 0}
{"_id": ObjectId ("55adba52fa1f3cf038c2aea9"), "name": "User3", "age": +, "Sex": 1}
{"_id": ObjectId ("55ADBA52FA1F3CF038C2AEAA"), "name": "User4", "age": +, "Sex": 0}
{"_id": ObjectId ("55adba52fa1f3cf038c2aeab"), "name": "User5", "age": +, "Sex": 1}
2, connect the database, get the set firstcollection
Mongoclient mclient = new Mongoclient ("10.211.55.8");
DB db = Mclient.getdb ("test");
Dbcollection collection = Db.getcollection ("firstcollection");
3. Query for the object name User1
Query criteria JSON content:
{"Name": "User1"}
Query condition Java content:
Basicdbobject queryobject = new Basicdbobject ("name", "User1");
Execution process:
DBObject obj = Collection.findone (queryobject);
So I got the name of User1 object.
4. Query name contains the object of user
Such a fuzzy query, similar to a like query, is done by regular expressions.
Query criteria JSON content:
{"Name":/user/}
Query condition Java content:
Pattern Querypattern = pattern.compile ("user", pattern.case_insensitive);
Basicdbobject queryobject = new Basicdbobject ("name", Querypattern);
Execution process:
Pattern Querypattern = pattern.compile ("user", pattern.case_insensitive);
Basicdbobject queryobject = new Basicdbobject ("name", Querypattern);
cursor cursor = Collection.find (queryobject);
while (Cursor.hasnext ()) {
DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
}
5. Search for objects older than 24
Query criteria JSON content:
{"Age": {"$GT": 24}}
Query condition Java content:
Nesting of two Bson objects
Basicdbobject GT = new Basicdbobject ("$gt", 24);
Basicdbobject queryobject = new Basicdbobject ("Age", GT);
Execution process:
Basicdbobject GT = new Basicdbobject ("$gt", 24);
Basicdbobject queryobject = new Basicdbobject ("Age", GT);
cursor cursor = Collection.find (queryobject);
while (Cursor.hasnext ()) {
DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
}
Note:
$GT:>
$gte: >=
$eq: =
$ne:! =
$LT: <
$lte: <=
$in: In (The following value is an array of Bson objects)
$nin: Not in (the following value is an array of Bson objects)
The use of these operators is similar to $GT, not repeating
Summarize
Through this article can be a simple query MongoDB, but in the specific business only simple query is unrealistic, there will be more with or relations, this play content will be described in the next article.
Java MongoDB Query (a) simple query