All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sagacity.sqltoy.solon.integration.SolonMongoQuery Maven / Gradle / Ivy

The newest version!
package org.sagacity.sqltoy.solon.integration;

import java.util.ArrayList;
import java.util.List;

import org.bson.BsonDocument;
import org.bson.Document;
import org.sagacity.sqltoy.SqlToyContext;
import org.sagacity.sqltoy.integration.MongoQuery;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class SolonMongoQuery implements MongoQuery {
    private MongoDatabase db;

    @Override
    public MongoCollection getCollection(String collectionName) {
        return db.getCollection(collectionName);
    }

    @Override
    public  List find(String query, Class entityClass, String collectionName, Long skip, Integer limit) {
        MongoCollection collection = getCollection(collectionName);
        FindIterable findIterable = collection.find(BsonDocument.parse(query), entityClass);

        if (skip != null) {
            findIterable.skip(skip.intValue());
        }
        if (limit != null) {
            findIterable.limit(limit);
        }

        MongoCursor cur = findIterable.iterator();

        List data = new ArrayList<>();

        while (cur.hasNext()) {
            data.add(cur.next());
        }
        cur.close();

        return data;
    }

    @Override
    public long count(String query, String collectionName) {
        MongoCollection collection = getCollection(collectionName);
        Document sum = new Document();
        sum.put("$sum", 1);

        Document count = new Document();
        count.put("_id", null);
        count.put("count", sum);

        Document group = new Document();
        group.put("$group", count);

        List list = new ArrayList();
        list.add(group);

        AggregateIterable iterable = collection.aggregate(list);
        MongoCursor cursor = iterable.iterator();
        while (cursor.hasNext()) {
            Document docu = cursor.next();
            return (Long) docu.get("count");
        }
        return 0;
    }

    @Override
    public void initialize(SqlToyContext sqlToyContext) {
        db = sqlToyContext.getAppContext().getBean(MongoDatabase.class);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy