org.springframework.data.mongodb.core.MongoOperations Java Examples

The following examples show how to use org.springframework.data.mongodb.core.MongoOperations. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoDbFixture.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
MongoDbFixture() {

		SpringApplication application = new SpringApplication();
		application.addPrimarySources(Collections.singletonList(MongoDbApplication.class));
		application.setAdditionalProfiles("jpa");
		application.setLazyInitialization(true);

		this.context = application.run();
		
		MongoOperations operations = context.getBean(MongoOperations.class);
		
		operations.dropCollection(Book.class);
		
		IntStream.range(0, Constants.NUMBER_OF_BOOKS) //
			.mapToObj(it -> new Book("title" + it, it)) //
			.forEach(operations::save);
	}
 
Example #2
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #3
Source File: SpringDataMongoDBMain.java    From journaldev with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	try {
		MongoClient mongo = new MongoClient(
				MONGO_HOST, MONGO_PORT);
		MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
		Person p = new Person("113", "PankajKr", "Bangalore, India");
		mongoOps.insert(p, PERSON_COLLECTION);

		Person p1 = mongoOps.findOne(
				new Query(Criteria.where("name").is("PankajKr")),
				Person.class, PERSON_COLLECTION);

		System.out.println(p1);
		
		mongoOps.dropCollection(PERSON_COLLECTION);
		mongo.close();
		
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}
 
Example #4
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #5
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #6
Source File: InitUsers.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner initializeUsers(MongoOperations operations) {
	return args -> {
		operations.dropCollection(User.class);

		operations.insert(
			new User(
				null,
				"greg", "turnquist",
				new String[]{"ROLE_USER", "ROLE_ADMIN"}));
		operations.insert(
			new User(
				null,
				"phil", "webb",
				new String[]{"ROLE_USER"}));

		operations.findAll(User.class).forEach(user -> {
			System.out.println("Loaded " + user);
		});
	};
}
 
Example #7
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #8
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #9
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #10
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #11
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
	};
}
 
Example #12
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #13
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #14
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg"));
		operations.insert(new Image("3",
			"bazinga.png"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #15
Source File: WebfluxDemo.java    From spring-five-functional-reactive with Apache License 2.0 6 votes vote down vote up
/**
 * Application runner to initialize a capped collection for {@link Event}s and insert a new {@link Event} every two
 * seconds.
 * 
 * @param operations
 * @param reactiveOperations
 * @return
 */
@Bean
ApplicationRunner onStart(MongoOperations operations, ReactiveMongoOperations reactiveOperations) {

	return args -> {

		CollectionOptions options = CollectionOptions.empty() //
				.capped() //
				.size(2048) //
				.maxDocuments(1000);

		operations.dropCollection(Event.class);
		operations.createCollection(Event.class, options);

		Flux.interval(Duration.ofSeconds(2)) //
				.map(counter -> new Event(LocalDateTime.now())) //
				.flatMap(reactiveOperations::save) //
				.log() //
				.subscribe();
	};
}
 
Example #16
Source File: StoreInitializer.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Autowired
public StoreInitializer(StoreRepository repository, MongoOperations operations) throws Exception {

	if (repository.count() != 0) {
		return;
	}

	Iterable<? extends IndexDefinition> indexDefinitions = IndexResolver
			.create(operations.getConverter().getMappingContext())
			.resolveIndexFor(Store.class);
	
	indexDefinitions.forEach(operations.indexOps(Store.class)::ensureIndex);

	List<Store> stores = readStores();
	log.info("Importing {} stores into MongoDB…", stores.size());
	repository.saveAll(stores);
	log.info("Successfully imported {} stores.", repository.count());
}
 
Example #17
Source File: InitDatabase.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(MongoOperations operations) {
	return args -> {
		// tag::log[]
		operations.dropCollection(Image.class);

		operations.insert(new Image("1",
			"learning-spring-boot-cover.jpg", "greg"));
		operations.insert(new Image("2",
			"learning-spring-boot-2nd-edition-cover.jpg", "greg"));
		operations.insert(new Image("3",
			"bazinga.png", "greg"));

		operations.findAll(Image.class).forEach(image -> {
			System.out.println(image.toString());
		});
		// end::log[]
	};
}
 
Example #18
Source File: ReservationsApplication.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
  InitializingBean initializingBean(final ReservationRepository reservations,
                                    final MongoOperations ops) {

    final AtomicLong atomicLong = new AtomicLong(1);
    final LocalDate base = LocalDate.now();

    if (ops.collectionExists(Reservation.class))
      ops.dropCollection(Reservation.class);

    ops.createCollection(Reservation.class, new CollectionOptions(1_000_000_000_000_000L, null, true));

    return () -> Flux.just(1, 2, 3)
                     .map(days -> new Reservation().setCheckIn(base.plusDays(atomicLong.incrementAndGet()))
                                                   .setCheckOut(base.plusDays(atomicLong.incrementAndGet())))
                     .flatMap(reservations::save)
                     .subscribe(r -> {
                       log.info("created: {}", r);
                       ops.executeCommand("db.runCommand({ convertToCapped: 'reservation', size: 1111111111 })");
                     });

/*
    return () -> Flux.just(1, 2)
                     .map(String::valueOf)
                     .map(string -> new Reservation().setCheckIn(LocalDate.now())
                                                     .setCheckOut(LocalDate.now().plusDays(1)))
                     .flatMap(reservations::save)
                     .subscribe(r -> log.info("created: {}", r));
*/
/*
    return () -> reservations.deleteAll()
                             .thenMany(
                                 Flux.just(1, 2)
                                     .map(String::valueOf)
                                     .map(string -> new Reservation().setCheckIn(LocalDate.now())
                                                                     .setCheckOut(LocalDate.now().plusDays(1)))
                                     .flatMap(reservations::save))
                             .subscribe(r -> log.info("created: {}", r));
*/
  }
 
Example #19
Source File: TestMongoKeeper.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@link MongoInitialize#truncate()}で<code>true</code>が指定されたときにMongoDBより指定されたCollectionをすべて削除します。
 * @param operations {@link MongoOperations}
 * @param config {@link MongoInitialize}
 */
protected void truncate(MongoOperations operations, MongoInitialize config) {
    if (config.truncate()) {
        L.info(Strings.substitute(R.getString("I-MONGO-TEST#0002"), Maps.hash("collectionName", config.collectionName())));
        operations.dropCollection(findCollectionName(config));
    }
}
 
Example #20
Source File: TestMongoKeeper.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * テストデータをMongoDBに登録します。
 * @param operations {@link MongoOperations}
 * @param executables 登録するJSONデータ
 * @param config {@link MongoInitialize}
 */
protected void insert(MongoOperations operations, Object executables, MongoInitialize config) {
    L.info(Strings.substitute(R.getString("I-MONGO-TEST#0003"), Maps.hash("value", executables.toString())));
    if (executables.getClass().isArray()) {
        List<Object> gen = Lists.gen((Object[])executables);
        operations.insert(gen, findCollectionName(config));
    } else {
        operations.insert(executables, findCollectionName(config));
    }
}
 
Example #21
Source File: AggregateMongoQuery.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link AbstractMongoQuery} from the given {@link MongoQueryMethod} and {@link MongoOperations}.
 *
 * @param method must not be {@literal null}.
 * @param projectionFactory - the projection factory
 */
@Autowired
public AggregateMongoQuery(Method method, RepositoryMetadata metadata, MongoOperations mongoOperations,
                           ProjectionFactory projectionFactory, MongoQueryExecutor queryExecutor) {
  super(new MongoQueryMethod(method, metadata, projectionFactory, mongoOperations.getConverter().getMappingContext()),
        mongoOperations);
  this.mongoOperations = mongoOperations;
  this.method = method;
  this.queryExecutor = queryExecutor;
}
 
Example #22
Source File: TestMongoKeeper.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * MongoDBを初期化します。
 * @param context 現在のテスト実行コンテキスト
 * @param config コンフィグ
 */
protected void initialize(TestContext context, MongoInitialize config) {
    String[] candidates = createFileLocationCandidates(context, config);
    MongoOperations operations = findMongoOperations(context, config);
    Class<?> mapping = findMapping(context, config);
    truncate(operations, config);
    if (mapping != Void.class) {
        String content = readJsonFile(candidates, context, config);
        Object executables = createExecutables(content, mapping);
        insert(operations, executables, config);
    }
}
 
Example #23
Source File: MongoConfig.java    From service-block-samples with Apache License 2.0 5 votes vote down vote up
@Bean
CommandLineRunner commandLineRunner(MongoOperations operations) {
    return (args) -> {
        // Setup the streaming data endpoint
        if (operations.collectionExists("tightCouplingEvent")) {
            operations.dropCollection("tightCouplingEvent");
        }
        if (operations.collectionExists("query")) {
            operations.dropCollection("query");
        }

        CollectionOptions options = new CollectionOptions(5242880, 100000, true);
        operations.createCollection("tightCouplingEvent", options);
    };
}
 
Example #24
Source File: MongoDbAuthorityRepositoryTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    template = createMock(MongoOperations.class);
    converter = createNiceMock(HydratingConverterFactory.class);
    repo = new MongoDbAuthorityRepository();
    repo.setTemplate(template);
    repo.setConverter(converter);

}
 
Example #25
Source File: MongoDbAuthorityRepositoryTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void getTemplate(){
    MongoOperations temp1;

    temp1 = repo.getTemplate();
    assertThat(temp1, is(sameInstance(template)));
}
 
Example #26
Source File: EventService.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@Autowired
public EventService(
        TenantRepository tenantRepository,
        MongoEventRepository mongoEventRepository,
        UserIdConverter userIdConverter,
        ClassIdConverter classIdConverter,
        MongoOperations mongoOperations,
        MongoEnrollmentRepository mongoEnrollmentRepository) {
  this.tenantRepository = tenantRepository;
  this.mongoEventRepository = mongoEventRepository;
  this.userIdConverter = userIdConverter;
  this.classIdConverter = classIdConverter;
  this.mongoOps = mongoOperations;
  this.mongoEnrollmentRepository = mongoEnrollmentRepository;
}
 
Example #27
Source File: MongoDbCategoryRepositoryTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
    categoryRepository = new MongoDbCategoryRepository();
    template = createMock(MongoOperations.class);
    converter = createMock(HydratingConverterFactory.class);
    categoryRepository.setConverter(converter);
    categoryRepository.setTemplate(template);
}
 
Example #28
Source File: MongoDbPortalPreferenceRepositoryTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
    preferenceRepository = new MongoDbPortalPreferenceRepository();
    template = createMock(MongoOperations.class);
    converter = createMock(HydratingConverterFactory.class);
    preferenceRepository.setConverter(converter);
    preferenceRepository.setTemplate(template);
}
 
Example #29
Source File: NonReactiveAggregateMongoQuery.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link AbstractMongoQuery} from the given {@link MongoQueryMethod} and {@link MongoOperations}.
 *
 * @param method must not be {@literal null}.
 * @param projectionFactory - the projection factory
 */
@Autowired
public NonReactiveAggregateMongoQuery(Method method, RepositoryMetadata metadata, MongoOperations mongoOperations,
                                      ProjectionFactory projectionFactory, MongoQueryExecutor queryExecutor) {
  super(new MongoQueryMethod(method, metadata, projectionFactory, mongoOperations.getConverter().getMappingContext()),
        mongoOperations,
        new SpelExpressionParser(),
        CONTEXT_PROVIDER);
  this.mongoOperations = mongoOperations;
  this.method = method;
  this.queryExecutor = queryExecutor;
}
 
Example #30
Source File: MongoDbAuthorityRepositoryTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void setTemplate(){
    MongoOperations temp1 = createNiceMock(MongoOperations.class);

    repo.setTemplate(temp1);
    assertThat(repo.getTemplate(), is(sameInstance(temp1)));

}