1.1.36. fejezet, NoSQL

Cassandra - kapcsolódó hivatkozások

Sedna - kapcsolódó hivatkozások

MongoDB - kapcsolódó hivatkozások

Konfiguráció:

 

MongoDB admin felhasználó létrehozása

> mongo
use admin
db.createUser(
  {
    user: "username",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

Kapcsolódás adatbázishoz jogosultság kezeléssel:

mongo --port 27017 -u "username" -p "password" --authenticationDatabase "admin"

Adatbázis elérése Java-val

A pom.xml tartalma:

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Homework4MongoDB</groupId>
  <artifactId>Homework4MongoDB</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Homework4MongoDB</name>
  <description>Test MongoDB</description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>org.mongodb</groupId>
  		<artifactId>mongo-java-driver</artifactId>
  		<version>3.7.0</version>
  	</dependency>
  </dependencies>
</project>

Java minta kód

import java.util.Date;
 
import org.bson.Document;
 
import com.mongodb.Block;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
 
public class Homework4MongoDB {
	public static void main(String[] args) {
		MongoClient mongoClient = MongoClients.create("mongodb://username:password@localhost:27017");
		//MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); //with NoAuth		
		MongoDatabase database = mongoClient.getDatabase("users");
		for (String name : database.listCollectionNames()) {
		    System.out.println(name);
		}
 
		Block<Document> printBlock = new Block<Document>() {
		       @Override
		       public void apply(final Document document) {
		           System.out.println(document.toJson());
		       }
		};
		MongoCollection<Document> collection = database.getCollection("user");
		collection.find().forEach(printBlock);
 
		MongoCollection<Document> table = database.getCollection("user");
		Document document = new Document("user","users");
		document.put("name", "mkyong");
		document.put("age", 30);
		document.put("createdDate", new Date());
		table.insertOne(document);
	}
}