Example usage for org.springframework.data.mongodb.core.query BasicQuery BasicQuery

List of usage examples for org.springframework.data.mongodb.core.query BasicQuery BasicQuery

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.query BasicQuery BasicQuery.

Prototype

public BasicQuery(Document queryObject) 

Source Link

Document

Create a new BasicQuery given a query Document .

Usage

From source file:core.App.java

public static void main(String[] args) {

    // For XML//ww  w. j ava  2  s .co m
    //ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
    // For Annotation
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

    //Student user = new Student("3", "federico", "solterman", "26-10-1990");
    // save
    //mongoOperation.save(user);
    // now user object got the created id.
    // System.out.println("1. user : " + user);
    // query to search user
    // Query searchUserQuery = new Query(Criteria.where("first_name").is("federico")) {
    //};
    // find the saved user again.
    //Student savedUser = mongoOperation.findOne(searchUserQuery, Student.class);
    // System.out.println("2. find - savedUser : " + savedUser);
    //This method  Fetch all students whose notes in a specific course were greater than 4
    BasicQuery query = new BasicQuery(
            "{ $and: [{ note_1: {$gt:4 }, note_2: {$gt:4}, note_3: {$gt:4},note_final:{$gt:4  } } ] }");

    List<StudentXCourseXNote> stu = mongoOperation.find(query, StudentXCourseXNote.class);
    StudentXCourseXNote aux;

    for (int i = 0; i < stu.size(); i++) {
        aux = stu.get(i);
        BasicQuery query1 = new BasicQuery("{id_registration:" + " \"" + aux.getId_student() + "\"}");

        Student student = mongoOperation.findOne(query1, Student.class);

        System.out.println(student.toString());

    }
    //Fetch all courses ordered by name for a given teacher
    BasicQuery query2 = new BasicQuery("{ last_name:\"Sulma\" }");

    Teacher teacher = mongoOperation.findOne(query2, Teacher.class);

    BasicQuery query3 = new BasicQuery("{  id_teacher: \"" + teacher.getId_teacher() + "\"}");

    List<TeacherXCourse> list = mongoOperation.find(query3, TeacherXCourse.class);

    TeacherXCourse aux2;

    for (int j = 0; j < list.size(); j++) {

        aux2 = list.get(j);

        BasicQuery query4 = new BasicQuery("{id_course: \"" + aux2.getId_course() + "\" }");

        Course course = mongoOperation.findOne(query4, Course.class);

        System.out.println(course.toString());

    }
    //This method add a new fields in the collection course
    BasicQuery queryPoint4 = new BasicQuery("{ },{ $set: { finish: boolean } },{ multi: true }");
    Update update = new Update();
    update.set("{}", "");
    mongoOperation.updateFirst(queryPoint4, null, Course.class);

    // update password
    /*mongoOperation.updateFirst(searchUserQuery,
     Update.update("password", "new password"), Student.class);*/
    // find the updated user object
    /*Student updatedUser = mongoOperation.findOne(searchUserQuery, Student.class);*/
    //System.out.println("3. updatedUser : " + updatedUser);
    // delete
    // mongoOperation.remove(searchUserQuery, Student.class);
    // List, it should be empty now.
    /* List<Student> listUser = mongoOperation.findAll(Student.class);
      System.out.println("4. Number of user = " + listUser.size());*/
}

From source file:com.skymobi.monitor.model.LogQueryTest.java

public void test_query() throws Exception {

    assertEquals("{ }", query.toQuery().toString());
    query.setStart("2012-06-08 10:00:00");

    assertEquals("{ \"timestamp\" : { \"$gt\" : { \"$date\" : \"2012-06-08T02:00:00.000Z\"}}}",
            query.toQuery().toString());
    query.setEnd("2012-06-08 11:00:00");
    query.setLevel("ERROR");
    query.setKeyWord("111");
    System.out.println(query.toQuery().toString());

    Query bquery = new BasicQuery(query.toQuery());
    bquery.limit(100);//  ww w  .  jav  a  2 s .c o m

    bquery.sort().on("$timestamp", Order.DESCENDING);
    System.out.println(bquery.getQueryObject());
    System.out.println(bquery.getFieldsObject());
    System.out.println(bquery.getSortObject());
    //        assertEquals("{ \"timestamp\" : { \"$gt\" : { \"$date\" : \"1970-01-01T00:01:40.000Z\"}} , \"$where\" : \"this.message && this.message.match('hello')\"}",query.toQuery().toString());
}

From source file:com.appleframework.monitor.model.LogQueryTest.java

public void test_query() throws Exception {

    assertEquals("{ }", query.toQuery().toString());
    query.setStart("2012-06-08 10:00:00");

    assertEquals("{ \"timestamp\" : { \"$gt\" : { \"$date\" : \"2012-06-08T02:00:00.000Z\"}}}",
            query.toQuery().toString());
    query.setEnd("2012-06-08 11:00:00");
    query.setLevel("ERROR");
    query.setKeyWord("111");
    System.out.println(query.toQuery().toString());

    Query bquery = new BasicQuery(query.toQuery());
    bquery.limit(100);//  w w  w .  j a va 2 s  .  com

    //bquery.sort().on("$timestamp", Order.DESCENDING);
    bquery.with(new Sort(Direction.DESC, "$timestamp"));
    System.out.println(bquery.getQueryObject());
    System.out.println(bquery.getFieldsObject());
    System.out.println(bquery.getSortObject());
    //        assertEquals("{ \"timestamp\" : { \"$gt\" : { \"$date\" : \"1970-01-01T00:01:40.000Z\"}} , \"$where\" : \"this.message && this.message.match('hello')\"}",query.toQuery().toString());
}

From source file:com.skymobi.monitor.service.LogsService.java

public DBCursor findLogs(String projectName, LogQuery logQuery, int max) throws ParseException {
    Project project = projectService.findProject(projectName);
    MongoTemplate template = project.fetchMongoTemplate();

    Query query = new BasicQuery(logQuery.toQuery());
    query.limit(max);/*from   ww w .  j a  va 2 s .com*/

    query.sort().on("timestamp", Order.DESCENDING);
    logger.debug("find logs from {}  by query {} by sort {}",
            new Object[] { project.getLogCollection(), query.getQueryObject(), query.getSortObject() });
    DBCursor cursor = template.getCollection(project.getLogCollection()).find(query.getQueryObject())
            .sort(query.getSortObject()).limit(max);
    return cursor;
}

From source file:com.appleframework.monitor.service.LogsService.java

public DBCursor findLogs(String projectName, LogQuery logQuery, int max) throws ParseException {
    Project project = projectService.findProject(projectName);
    MongoTemplate template = project.fetchMongoTemplate();

    Query query = new BasicQuery(logQuery.toQuery());
    query.limit(max);/*from   w  w  w. j  av a  2  s .  co  m*/

    //query.sort().on("timestamp", Order.DESCENDING);
    query.with(new Sort(Direction.DESC, "timestamp"));
    logger.debug("find logs from {}  by query {} by sort {}",
            new Object[] { project.getLogCollection(), query.getQueryObject(), query.getSortObject() });
    DBCursor cursor = template.getCollection(project.getLogCollection()).find(query.getQueryObject())
            .sort(query.getSortObject()).limit(max);
    return cursor;
}

From source file:io.github.microcks.repository.GenericResourceRepositoryImpl.java

@Override
public List<GenericResource> findByServiceIdAndJSONQuery(String serviceId, String jsonQuery) {
    // First parse query document and prepare a list of key to rename then remove.
    Document query = Document.parse(jsonQuery);
    ArrayList<String> keysToRemove = new ArrayList<>();

    // Collect the keys of document that should be updated.
    for (String key : query.keySet()) {
        keysToRemove.add(key);//  www. ja va2s . co  m
    }
    // Prefix all keys by payload. that is the nested document where we put resource in
    // and remove all modified keys.
    for (String keyToRemove : keysToRemove) {
        query.append("payload." + keyToRemove, query.get(keyToRemove));
        query.remove(keyToRemove);
    }

    // Finally, append serviceId criterion before launching selection.
    query.append("serviceId", serviceId);

    return template.find(new BasicQuery(query.toJson()), GenericResource.class);
}

From source file:com.card.loop.xyz.dao.LearningElementDAO.java

public List<LearningElement> searchLE(String keyword) {
    //return mongoOps.findAll(LearningElement.class);
    //Query query = new Query();
    BasicQuery query = new BasicQuery("{\"title\": {$regex : '/" + keyword + "/'} }");
    //       System.out.println(query+"HAHA");
    query.limit(10);/*from   w  w w.  ja v a 2  s .  c o  m*/
    //query.addCriteria(where("title").is(keyword).orOperator(where("subject").is(keyword)).orOperator(where("description").is(keyword)));
    //query.addCriteria(Criteria.where("title").regex(keyword));
    System.out.println(query);
    //return mongoOps.find(query(where("title").regex(keyword)), LearningElement.class);
    return mongoOps.find(query(where("status").is(1)), LearningElement.class);
}

From source file:example.springdata.mongodb.geojson.StoreRepositoryTests.java

/**
 * The {@code $geoIntersects} keyword is not yet available via {@link Criteria} we need to fall back to manual
 * creation of the query using the registered {@link MongoConverter} for {@link GeoJson} conversion.
 *//*from ww  w.jav a  2s . c  o  m*/
@Test
public void findStoresThatIntersectGivenPolygon() {

    DBObject geoJsonDbo = new BasicDBObject();

    operations.getConverter().write(GEO_JSON_POLYGON, geoJsonDbo);

    BasicQuery bq = new BasicQuery(new BasicDBObject("location",
            new BasicDBObject("$geoIntersects", new BasicDBObject("$geometry", geoJsonDbo))));

    operations.find(bq, Store.class).forEach(System.out::println);
}

From source file:com.traffitruck.service.MongoDAO.java

public Collection<Alert> getAlertsByFilter(Double sourceLat, Double sourceLng, Integer source_radius,
        Double destinationLat, Double destinationLng, Integer destination_radius) {
    // get alerts with source and destination both exist and match
    // add alerts where the source is a match and the destination is not set 
    // add alerts where the destination is a match and the source is not set 

    List<Alert> coll = null;

    // get alerts with source and destination both exist and match
    {/*  w  w  w .  j  a v  a  2 s.c  o m*/
        // The criteria API isn't good enough
        String query = "{";
        if (sourceLat != null && sourceLng != null && source_radius != null) {
            if (query.length() > 1) {
                query += ", ";
            }
            query += "sourceLocation : { $geoWithin : { $centerSphere: [ [" + sourceLng + ", " + sourceLat
                    + "], " + source_radius / EARTH_RADIUS_IN_RADIANS + "] } }";
        }
        if (destinationLat != null && destinationLng != null && destination_radius != null) {
            if (query.length() > 1) {
                query += ", ";
            }
            query += "destinationLocation : { $geoWithin : { $centerSphere: [ [" + destinationLng + ", "
                    + destinationLat + "], " + destination_radius / EARTH_RADIUS_IN_RADIANS + "] } }";
        }
        query += "}";
        BasicQuery queryobj = new BasicQuery(query);
        coll = mongoTemplate.find(queryobj, Alert.class);
    }

    // add alerts where the source is a match and the destination is not set 
    {
        String noDestquery = "{";
        if (sourceLat != null && sourceLng != null && source_radius != null) {
            if (noDestquery.length() > 1) {
                noDestquery += ", ";
            }
            noDestquery += "sourceLocation : { $geoWithin : { $centerSphere: [ [" + sourceLng + ", " + sourceLat
                    + "], " + source_radius / EARTH_RADIUS_IN_RADIANS + "] } }";
        }
        if (destinationLat != null && destinationLng != null && destination_radius != null) {
            if (noDestquery.length() > 1) {
                noDestquery += ", ";
            }
            noDestquery += "destinationLocation : { $exists: false }";
        }
        noDestquery += "}";
        BasicQuery queryobj = new BasicQuery(noDestquery);
        coll.addAll(mongoTemplate.find(queryobj, Alert.class));
    }

    // add alerts where the destination is a match and the source is not set 
    {
        String noSourcequery = "{";
        if (sourceLat != null && sourceLng != null && source_radius != null) {
            if (noSourcequery.length() > 1) {
                noSourcequery += ", ";
            }
            noSourcequery += "sourceLocation : { $exists: false }";
        }
        if (destinationLat != null && destinationLng != null && destination_radius != null) {
            if (noSourcequery.length() > 1) {
                noSourcequery += ", ";
            }
            noSourcequery += "destinationLocation : { $geoWithin : { $centerSphere: [ [" + destinationLng + ", "
                    + destinationLat + "], " + destination_radius / EARTH_RADIUS_IN_RADIANS + "] } }";
        }
        noSourcequery += "}";
        BasicQuery queryobj = new BasicQuery(noSourcequery);
        coll.addAll(mongoTemplate.find(queryobj, Alert.class));
    }
    return new HashSet<Alert>(coll);
}

From source file:de.steilerdev.myVerein.server.model.GridFSRepository.java

/**
 * This function should delete the complete collection.
 * Todo: Check!/*from  w  w w. ja v a2 s.  c o m*/
 */
public void deleteAll() {
    gridFS.delete(new BasicQuery("{}"));
}