Objective
In the previous "Java MongoDB query (a) simple query" We have a simple look at the following query, but only those queries are not enough, but also need complex queries, this is described in this article.
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, and query
Operator: $and
Scenario: Querying an object with age greater than 23 and a sex of 1
Query criteria JSON content:
{"$and": [{"Age": {"$gt": 23}},{"Sex": 1}]}
Query condition Java content:
Basicdbobject ageobj = new Basicdbobject ("Age", New Basicdbobject ("$gt", 23));
Basicdbobject sexobj = new Basicdbobject ("Sex", 1);
Basicdbobject andobj = new Basicdbobject ("$and", Arrays.aslist (Ageobj,sexobj));
Execution process:
cursor cursor = Collection.find (andobj);
while (Cursor.hasnext ()) {
DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
}
4, or query
Operator: $or
Scenario: Query for Name User2, or object named User3
Query criteria JSON content:
{"$or": [{"Name": "User2"},{"name": "User3"}]}
Query condition Java content:
Basicdbobject user2obj = new Basicdbobject ("name", "User2");
Basicdbobject user3obj = new Basicdbobject ("name", "User3");
Basicdbobject orobj = new Basicdbobject ("$or", Arrays.aslist (User2obj,user3obj));
Execution process:
cursor cursor = Collection.find (orobj);
while (Cursor.hasnext ()) {
DBObject obj = Cursor.next ();
System.out.println (Obj.tostring ());
}
5. Summary
Through the query with or, we understand the way of query conditions combination, in this way, and then contact the "Java MongoDB Query (a) Simple query" content can be combined into the various results we want to query conditions.
Java MongoDB Query (ii) complex queries