@zero1036
2017-05-31T10:42:07.000000Z
字数 1872
阅读 1733
Mongodb-Client Mongodb
操作符:["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"],适用于Datastore.find()及Query.filter()
注意:十分要注意:所有的操作符与字段名,必须留空格,例如:Age!=22,就会报错
Datastore.find()示例:
//年龄22的用户:{Age:22}List<Customer> list = datastore.find(Customer.class, "Age =", 22).asList();//等价于以上list = datastore.find(Customer.class, "Age", 22).asList();//年龄22以上的用户:{Age:{$gt:22}}list = datastore.find(Customer.class, "Age >", 22).asList();//名字是Tgor、Mark其中一位的用户:{Name:{$in:["Tgor","Mark"]}}list = datastore.find(Customer.class, "Name in", new String[]{"Tgor", "Mark"}).asList();//名字不在Tgor、Mark之间的用户:{Name:{$nin:["Tgor","Mark"]}}list = datastore.find(Customer.class, "Name nin", new String[]{"Tgor", "Mark"}).asList();//角色是A、B、C其中之一的用户:{Role:{$in:["A","B","C"]}}。结果失败,所有用户都会查出,role字段是数组,应使用$alllist = datastore.find(Customer.class, "Role in", new String[]{"A", "B", "C"}).asList();//全部具有A、B、C三种角色的用户:{Role:{$all:["A","B","C"]}}。结果失败,所有用户都会查出,role字段是数组,应使用$alllist = datastore.find(Customer.class, "Role all", new String[]{"A", "B", "C"}).asList();//具有3种角色的用户:list = datastore.find(Customer.class, "Role size", 3).asList();//年龄不等于28的用户:{Age:{$ne:28}}list = datastore.find(Customer.class, "Age !=", 28).asList();
通过find()查询,find api只支持单个条件参数,对于复合查询,需要使用Query.filter(),示例:
注意:
Query<Customer> qry = datastore.createQuery(Customer.class);//年龄22以上,且具有C角色的用户:{$and:[{Age:{$gt:22}},{Role:{$all:["C"]}}]}List<Customer> list = qry.filter("Age >", 22).filter("Role all", new String[]{"C"}).asList();//注意:filter()拼接方法只支持and//年龄22以上,或具有C角色的用户:{ "$or" : [ { "Age" : { "$gt" : 22}} , { "Role" : { "$all" : [ "C"]}}]}List<String> roles = new ArrayList<String>();roles.add("C");qry.or(qry.criteria("Age").greaterThan(22), qry.criteria("Role").hasAllOf(roles));List<Customer> list = qry.asList();System.out.println("打印查询条件:" + qry.toString());
Query<Customer> qry = datastore.createQuery(Customer.class);//根据手机升序,再根据年龄降序List<Customer> list = qry.order("Phone,-Age").asList();