Adding a Document to an Array in MongoDB

1

This week, I started messing with MongoDB (I've never had much contact with any DB before) and a question has just come up that I can not solve (I researched, believe).

Let's go to the following context:

    @Listener(targets = ExceptionUncaughtEvent.class)
private static void onException(ExceptionUncaughtEvent e){
    MongoCollection<Document> col = DogoBot.db.getCollection("BOT");

    if(!col.find(new Document().append("ID", "STATISTICS")).first().containsKey("EXCEPTIONS")){
        col.findOneAndUpdate(new Document().append("ID", "STATISTICS"), new Document().append("$set", new Document("EXCEPTIONS", new ArrayList<Document>())));
    }
    Document doc = new Document()
            .append("CLASS", e.getClass().getName())
            .append("DATE", Calendar.getInstance().getTime())
            .append("WARN_LEVEL", e.getWarnLevel().toString());
    col.updateOne(
            new Document().append("ID", "STATISTICS"),
            new Document().append("$push", new Document().append("EXCEPTIONS", doc)));
    e.getReporter().report();
}

And in the Database, I have:

{ "_id" : ObjectId("5a18b83a252ee4305cc83880"), "ID" : "STATISTICS", "EXCEPTIONS" : [ ] }

My goal here is to first check if there is an array called "EXCEPTIONS", if it does not exist, create one. (I do not know if this step is necessary, if not please let me know).

Following this, create a Document with all the Exception information that has occurred, and add it to array EXCEPTIONS in the Database.

However, this does not happen (instead, in the collection, you create multiple Documents "

asked by anonymous 25.11.2017 / 01:44

0 answers