1

I'm trying to find the best solution for running and querying an in-memory MongoDb in Java.

I looked around for the right solution, and found Fongo, which is no longer developed/supported.

My needs are:

  1. Support MongoDb 4.2 and future releases.
  2. Be able to fast insert a document and query it in memory.
  3. Stable in a matter of staying in memory for long periods.
  4. Relatively small memory consumption.

I'll be glad to hear about recommended projects.

SharonBL
  • 1,735
  • 5
  • 20
  • 28

1 Answers1

2

I think now the only option is Embedded MongoDB.

Here is the github project.
And here the maven repository.

And a Baeldung guide where show this example:

@DataMongoTest
@ExtendWith(SpringExtension.class)
public class MongoDbSpringIntegrationTest {
    @DisplayName("given object to save"
        + " when save object using MongoDB template"
        + " then object is saved")
    @Test
    public void test(@Autowired MongoTemplate mongoTemplate) {
        // given
        DBObject objectToSave = BasicDBObjectBuilder.start()
            .add("key", "value")
            .get();

        // when
        mongoTemplate.save(objectToSave, "collection");

        // then
        assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
            .containsOnly("value");
    }
}

And another example is in this question updated in 2022.

@Test
public void shouldCreateNewObjectInEmbeddedMongoDb() {
    // given
    MongoDatabase db = mongo.getDatabase(DATABASE_NAME);
    db.createCollection("testCollection");
    MongoCollection<BasicDBObject> col = db.getCollection("testCollection", BasicDBObject.class);

    // when
    col.insertOne(new BasicDBObject("testDoc", new Date()));

    // then
    assertEquals(1L, col.countDocuments());
}
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • 1
    it's a good way but note that in Baeldung article he say explicitly: "using an embedded server cannot be considered as “full integration testing”. Flapdoodle's embedded MongoDB isn't an official MongoDB product. Therefore, we cannot be sure that it behaves exactly as in the production environment." – Paolo Biavati Feb 17 '23 at 09:18