Add a Document to an Array in Mongodb

Asked

Viewed 161 times

1

This week, I started messing with Mongodb (I’ve never had much contact with any DB before) and a question just came up that I’m not able to solve(I researched, believe me).

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 on 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 it is not to warn me please).

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

However, this does not happen (instead, in Colection, several documents are created "{"EXCEPTIONS":[]}" ).

Does anyone know why? Can you explain to me why this doesn’t work? Thank you people

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.