Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.tengen;
- import com.mongodb.*;
- import de.flapdoodle.embed.mongo.MongodExecutable;
- import de.flapdoodle.embed.mongo.MongodProcess;
- import de.flapdoodle.embed.mongo.MongodStarter;
- import de.flapdoodle.embed.mongo.config.IMongodConfig;
- import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
- import de.flapdoodle.embed.mongo.config.Net;
- import de.flapdoodle.embed.mongo.distribution.Version;
- import de.flapdoodle.embed.process.runtime.Network;
- import java.io.IOException;
- import java.util.Arrays;
- import java.util.List;
- public class UpdateRemoveTestMock {
- public static void main(String[] args) throws IOException {
- MongodStarter starter = MongodStarter.getDefaultInstance();
- int port = 12345;
- IMongodConfig mongodConfig = new MongodConfigBuilder()
- .version(Version.Main.PRODUCTION)
- .net(new Net(port, Network.localhostIsIPv6()))
- .build();
- MongodExecutable mongodExecutable = null;
- MongodProcess mongod = null;
- try {
- mongodExecutable = starter.prepare(mongodConfig);
- mongod = mongodExecutable.start();
- Mongo mongo = new Mongo("localhost", port);
- DB db = mongo.getDB("course");
- DBCollection collection = db.getCollection("UpdateRemoveTest");
- collection.drop();
- List<String> names = Arrays.asList("alice", "bobby", "cathy", "david", "ethan");
- for (String name : names) {
- collection.insert(new BasicDBObject("_id", name));
- }
- // see scratch method
- scratch(collection);
- printCollection(collection);
- } finally {
- if (mongod != null && mongod.isProcessRunning())
- mongod.stop();
- if (mongodExecutable != null)
- mongodExecutable.stop();
- }
- }
- // these are all the statement I used throughout the lecture.
- private static void scratch(DBCollection collection) {
- collection.update(new BasicDBObject("_id", "alice"),
- new BasicDBObject("age", 24));
- collection.update(new BasicDBObject("_id", "alice"),
- new BasicDBObject(new BasicDBObject("gender", "F")));
- collection.update(new BasicDBObject("_id", "alice"),
- new BasicDBObject("$set", new BasicDBObject("age", 24)));
- collection.update(new BasicDBObject("_id", "frank"),
- new BasicDBObject("$set", new BasicDBObject("age", 24)), true, false);
- collection.update(new BasicDBObject(),
- new BasicDBObject("$set", new BasicDBObject("title", "Dr")), false, true);
- collection.remove(new BasicDBObject("_id", "frank"));
- }
- private static void printCollection(final DBCollection collection) {
- DBCursor cursor = collection.find().sort(new BasicDBObject("_id", 1));
- try {
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
- }
- } finally {
- cursor.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement