Special operations (and or queries, fuzzy queries, range queries, data sorting, etc.) when connecting to MongoDB under the play framework

Keywords: Java MongoDB SQL less

Existing class information sheets:

package models;

import play.modules.mongo.MongoEntity;
import play.modules.mongo.MongoModel;

/**
 * Created by adinlead on 17/03/04.
 */
@MongoEntity("class_msg")
public class ClassMsg extends MongoModel {
    public Integer class;   //Class number
    public Integer number;   //Student ID
    public String name;   //Student name
    public Integer age; //Age
}

1. With or Query

1.1 and queries (similar to AND in SQL)

Nothing to say. That's the most basic thing.

1.2 or queries (similar to OR in SQL)

When doing or querying, you need to load conditions into a query object (com.mongodb.BasicDBObject) or a query list (com.mongodb.BasicDBList)
Specifically as follows:
Inquire all the students in a class, or those named "Yang Luo" or "Lin Yu":

BasicDBList params = new BasicDBList();
params.add(new BasicDBObject("name", "Yang Luo"));
params.add(new BasicDBObject("name", "Lin Yu"));
List<ClassMsg> resultList = ClassMsg.find("byClassAnd$or",1,params).fetch();

2. Fuzzy Query

Regular expressions are needed when connecting to Mongo for ambiguous queries
Here you can use the java.util.regex.Pattern object
Specifically as follows:
Inquire about Yang's family name

Pattern pattern = Pattern.compile("^Yang.*$", Pattern.CASE_INSENSITIVE);
List<ClassMsg> resultList = ClassMsg.find("byName",pattern).fetch();

3. Range query

Range queries are relatively simple, requiring only com.mongodb.BasicDBObject objects
Specifically as follows:
Inquire about a class of students aged over or equal to 20

/**
Greater than use: "$gt"
Greater than or equal to use: "$gte"
Less than used: "$lt"
Less than or equal to use: "$lte"
Not equal to using: "$ne"
Other situations can be queried in the MongoDB tutorial
**/
// The conditions need to be declared first
BasicDBObject param = new BasicDBObject("$gte",20)
List<ClassMsg> resultList = MongoModel.find("byAge",param).fetch();

X. sorting

The sort operation of the play framework framework is performed after the query condition is input and before the data is obtained.
Note that since the official documents were not written in reverse order, I checked the source code, which he defined as follows:
If a minus sign ('-') is added before the condition, the order of the condition is in reverse order. Otherwise, the order of the condition is positive by default.
Specifically as follows:
Sort by student number

// Reverse order
List<ClassMsg> resultList = MongoModel.find().order("by-number").fetch();
// Positive sequence arrangement
List<ClassMsg> resultList = MongoModel.find().order("byNumber").fetch();

Query examples:

Search class one's Yang surname or classmates older than 20 years old, and rank them according to their school numbers.

BasicDBList params = new BasicDBList();
Pattern pattern = Pattern.compile("^Yang.*$", Pattern.CASE_INSENSITIVE);
params.add(new BasicDBObject("name", pattern));
params.add(new BasicDBObject("age", new BasicDBObject("$gte",20)));
List<ClassMsg> resultList = ClassMsg.find("byClassAnd$or",1,params).order("byNumber").fetch();

Attached.

Since the query conditions may not be fixed in the actual production environment, and MongoModel does not support directly passing in the parameter list, I have written a simple query tool, I hope you do not laugh at it.

In order to improve your abilities (actually I'm lazy), I didn't write any notes.~

package utils;

import play.modules.mongo.MongoCursor;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by adinlead on 16/11/04.
 */
public class MongoQuery {

    public static MongoCursor doQuery(Class<?> clazz, String queryStr, Object[] params) {
        try {
            Object single = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("find", String.class, Array.newInstance(Object.class, 0).getClass());
            return (MongoCursor) method.invoke(single, new Object[]{queryStr, params});
        } catch (Exception e) {
            return null;
        }
    }

    public static MongoCursor doQuery(Class<?> clazz, String queryStr, List params) {
        return doQuery(clazz, queryStr, params.toArray());
    }

    public static MongoCursor doQuery(Class<?> clazz, StringBuilder queryStr, List params) {
        return doQuery(clazz, queryStr.toString(), params.toArray());
    }

    public static Long doCount(Class<?> clazz, String queryStr, Object[] params) {
        try {
            Object single = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("count", String.class, Array.newInstance(Object.class, 0).getClass());
            return (Long) method.invoke(single, new Object[]{queryStr, params});
        } catch (Exception e) {
            return null;
        }
    }

    public static Long doCount(Class<?> clazz, String queryStr, List params) {
        return doCount(clazz, queryStr, params.toArray());
    }

    public static Long doCount(Class<?> clazz, StringBuilder queryStr, List params) {
        return doCount(clazz, queryStr.toString(), params.toArray());
    }
}

Posted by melvincr on Sun, 14 Apr 2019 15:18:32 -0700