Equivalent of $objectToArray using Mongodb java driver 3

I am moving a Mongodb query from Javascript to Java. The object format is as follows:

I am moving a Mongodb query from Javascript to Java. The object format is as follows:

{
  "record": {
    "unknownName1": {
      "count": 5,
      "domain": "domain1"
    }, {
    ...
    }, {
    "unknownNameN": {
      "count": 3,
      "domain": "domainN"
    }
  }
}

The Javascript query has the following portion:

[
  { 
    $project: {
      record: { 
        $objectToArray: "$record" 
      }
    }
  }, {
    $unwind: { "$record"
  }, {
    $group: {
      device: "$record.k"
    }, 
    count: {
      $sum: "$record.v.count"
    },
    domain: {
      $min: "$record.v.domain"
    }
  }
]

I have translated the above to use the Mongodb Java Driver 3 api and have the following:

List<Bson> query = Arrays.asList(
    project(include("record")),
    unwind("$record"),
    group(computed("device", "$record.k"),
        sum("count", "$record.v.count"),
        min("domain", "$record.v.domain"))
);

The issue I am having is I can't seem to find an equivalent to $objectToArray using the Mongodb Java Driver and the subsequent sum and min operations depend on dot operating the k and v values generated from using $objectToArray.

Is there an equivalent way to map an object with unknown key names into the k and v format used by $objectToArray using the Mongodb Java Driver, preferrably version 3+?

Explore MongoDB in a Java application for basic usage.

Explore MongoDB in a Java application for basic usage.

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine.

In day-to-day life in the industry, we have data to be saved and fetched from any persistence source. The persistence source can be SQL, NoSQL, or other types. MongoDB is a NoSQL database. Sometimes we need a small tool to look at data or delete data in MongoDB. For quick development, we need a solution/layer/UI that simplifies our task.

MongoDB holds data in the form of a document, so any data that needs to be stored has to be converted into a MongoDB Document, and it's a cumbersome task, in general. To make things easier, we need a helper/util java class. MongoDB Java framework provides a mechanism to implement the same. The following enum class helps to do so. Through this enum class, the data that exists in any POJO can be saved/queried/updated with ease. The enum class can fetch the MongoDB collection data with the default security mechanism.

public enum MongoUtility {
    INSTANCE;
    private final Map<String, MongoDatabase> databaseMap = new HashMap<>();
    private final CodecRegistry pojoCodecRegistry;
    private final MongoClient mongo;
    private MongoUtility() {
        pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        mongo = new MongoClient();
    }
    public void closeMongoDB() {
        Optional.of(mongo).ifPresent(mongoInstance -> mongoInstance.close());
    }
    public MongoDatabase getDatabase(String database) {
        Optional<MongoDatabase> mongoDBOptional = Optional.ofNullable(databaseMap.get(database));
        return mongoDBOptional.orElseGet(createMongoDatabaseInstance(database));
    }
    private Supplier<MongoDatabase> createMongoDatabaseInstance(String database) {
        return () -> {
            MongoDatabase mongoDB = mongo.getDatabase(database);
            mongoDB = mongoDB.withCodecRegistry(pojoCodecRegistry);
            databaseMap.put(database, mongoDB);
            return mongoDB;
        };
    }
    public <T> MongoCollection<T> getBucket(String database, String bucket, Class<T> cls) {
        MongoDatabase mongoDB = getDatabase(database);
        return mongoDB.getCollection(bucket, cls);
    }
}

The above implementation can be achieved in Maven by putting the dependency in the pom.xml file.

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.10.2</version>
</dependency>

So, the framework can get things done with the least amount of effort.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on https://dzone.com

How to connect ScyllaDB with Java

How to connect ScyllaDB with Java

This post gives you Introducing ScyllaDB With Jav, and an overview of ScyllaDB, how to connect with Java using Jakarta EE.

From Wikipedia: "Scylla is an open-source distributed NoSQL data store. It was designed to be compatible with Apache Cassandra while achieving significantly higher throughputs and lower latencies. It supports the same protocols as Cassandra (CQL and Thrift) and the same file formats (SSTable), but is a completely rewritten implementation, using the C++17 language replacing Cassandra's Java, and the Seastar asynchronous programming library replacing threads, shared memory, mapped files, and other classic Linux programming techniques."

This post will test the ScyllaDB with Java and give you the first impression of this database, which is compatible with Apache Cassandra.

Installation

The first step in this tutorial is to install the Scylla database. To make this process easier, we will use Docker, which simplifies a lot of the installation process with just this command:

docker run -d --name scylladb-instance -p 9042:9042 scylladb/scylla
Infrastructure Code

In a Maven project, we need to set the dependency project. Eclipse JNoSQL has two layers: one for mapping and the other one for communication. Once ScyllaDB is compatible with Cassandra, this post will use the Cassandra driver as the dependency for communication. Furthermore, it important to set a CDI implementation.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>scylla</artifactId>
  <name>Artemis Demo using Java SE scylla</name>

  <parent>
    <groupId>org.jnosql.artemis</groupId>
    <artifactId>artemis-demo-java-se</artifactId>
    <version>0.0.9</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.jnosql.artemis</groupId>
      <artifactId>cassandra-extension</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

</project>

Show Me the Code

For this sample, we have the Person entity with idname, and phones as fields:

import org.jnosql.artemis.Column;
import org.jnosql.artemis.Entity;
import org.jnosql.artemis.Id;

import java.util.List;

@Entity("Person")
public class Person {

  @Id("id")
  private long id;

  @Column
  private String name;

  @Column
  private List<String> phones;

}

There is a Repository interface that implements the basic operations in the database. Also, it has the method query, which gives the method that Eclipse JNoSQL will implement to the Java developer:

import org.jnosql.artemis.Repository;

public interface PersonRepository extends Repository<Person, Long> {

}

The next step is to make a connection, an entity manager, available to CDI.

import org.jnosql.diana.cassandra.column.CassandraColumnFamilyManager;
import org.jnosql.diana.cassandra.column.CassandraColumnFamilyManagerFactory;
import org.jnosql.diana.cassandra.column.CassandraConfiguration;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class ScyllaProducer {

private static final String KEY_SPACE = "developers";

private CassandraConfiguration cassandraConfiguration;

private CassandraColumnFamilyManagerFactory managerFactory;

@PostConstruct

public void init() {
    cassandraConfiguration = new CassandraConfiguration();
    managerFactory = cassandraConfiguration.get();
}

@Produces
public CassandraColumnFamilyManager getManagerCassandra() {
    return managerFactory.get(KEY_SPACE);
}

}

The ScyllaProducer class makes a manager entity class available and ready for the application use. Once the code does not define the Settings, it will use the default behavior, so it will read from the diana-cassandra.properties file. This file has the configuration startup, thus the port and host to connect. Scylla as Cassandra is not schemaless, which means we need to create the structure before we use it. The properties file has Cassandra Query Language to create the keyspace and the column family structure.

cassandra.host.1=localhost
cassandra.query.1=CREATE KEYSPACE IF NOT EXISTS developers WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
cassandra.query.2=CREATE COLUMNFAMILY IF NOT EXISTS developers.Person (id bigint PRIMARY KEY, name text, phones list<text>);

The whole configuration process and the code are ready, so let's run the code!


import org.jnosql.artemis.cassandra.column.CassandraTemplate;
import org.jnosql.artemis.column.ColumnTemplate;
import org.jnosql.diana.api.column.ColumnQuery;

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
import java.util.Arrays;
import java.util.Optional;

import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.select;

public class App {

public static void main(String[] args) {

    try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        ColumnTemplate template = container.select(CassandraTemplate.class).get();
        Person saved = template.insert(person);
        System.out.println("Person saved" + saved);

        ColumnQuery query = select().from("Person").where("id").eq(1L).build();

        Optional&lt;Person&gt; result = template.singleResult(query);
        System.out.println("Entity found: " + result);

    }
}

private App() {
}

}

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
import java.util.Arrays;
import java.util.Optional;

import static org.jnosql.artemis.DatabaseQualifier.ofColumn;

public class App2 {

public static void main(String[] args) {

    try(SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        PersonRepository repository = container.select(PersonRepository.class).select(ofColumn()).get();
        Person saved = repository.save(person);
        System.out.println("Person saved" + saved);

        Optional&lt;Person&gt; result = repository.findById(1L);
        System.out.println("Entity found: " + person);

    }
}

private App2() {}

}

We now have the ability to run a particular behavior in a NoSQL database matter! That's why the Eclipse JNoSQL worries about the extensibility of both Cassandra and ScyllaDB and worries about the support to native query the CQL and operation with consistency level. To support it and move resources, there is the CassandraTemplate, which is an extension of ColumnTemplate and allows features from Cassandra as a consequence on ScyllaDB.

import com.datastax.driver.core.ConsistencyLevel;
import org.jnosql.artemis.cassandra.column.CassandraTemplate;
import org.jnosql.diana.api.column.ColumnQuery;

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
import java.util.Arrays;
import java.util.List;

import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.select;

public class App3 {

public static void main(String[] args) {

    try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        CassandraTemplate cassandraTemplate = container.select(CassandraTemplate.class).get();
        Person saved = cassandraTemplate.save(person, ConsistencyLevel.ONE);
        System.out.println("Person saved" + saved);
        List&lt;Person&gt; people = cassandraTemplate.cql("select * from developers.Person where id = 1");
        System.out.println("Entity found: " + people);

    }
}

private App3() {
}

}

This post gives you an overview of ScyllaDB and how to connect with Java using Jakarta EE. ScyllaDB has compatibility with Cassandra that allows us to use the same Cassandra API without issues. 

Thank you for reading!


Originally published on https://dzone.com

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB - Part 3/3

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB

What you’ll learn

  • Work with MongoDB with Clarity and Confidence
  • Use 4 tools MongoCHEF, NOSQL Manager, RoboMongo, MongoBooster easily
  • Do Regex, GridFS , Replication , Sharding, Full text search
  • Basic and Advanced CRUD operations using MongoDB
  • Import and Export data from MongoDB
  • Work MapReduce, Embedded Documents,Save&Insert , indexing, capped collections, TTL
  • Bonus section * Use java,C#,PHP,Nodejs to access MongoDB features like CRUD, GridFS
  • Bonus Section * A 50 minutes MongoDB key feature exercises
  • 100+ Quizzes 40+ Activities

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

MongoDB - The Complete Developer’s Guide

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

Build a CRUD Operation using PHP & MongoBD

MongoDB with Python Crash Course - Tutorial for Beginners

Learn NoSQL Databases from Scratch - Complete MongoDB Bootcamp 2019

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Creating RESTful APIs with NodeJS and MongoDB Tutorial