I am a little confused as to how to add an element to an array in an exisiting mongodb document, or why my results are not showing properly and how I expect.
There is only one document in the collection and will only ever be one. The mongo document looks like when I do a db.collection-name.find.pretty()
command in a mongo session on the command line:
{
"_id" : ObjectID("1234567890"),
"details" : {
...
},
"calculations" : [
{
"count" : 1,
"total" : 10,
"mean" : 2.5
},
{
"count" : 2,
"total" : 20,
"mean" : 6.4
}
]
}
I want to add another object to the calculations
list.
The Java code I am running is based upon THIS example:
// Get the database and collection
MongoDatabase database = mongo.getDatabase(dataBaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);
Document document = collection.find().first(); // will only ever be one document
// The object comes in as a Map
Map<String, Object> incomingMap = new HashMap<>();
incomingMap.put("count", 3);
incomingMap.put("total", 4);
incomingMap.put("mean", 7.9);
// convert to a Document
Document newDocument = new Document();
incomingMap.forEach((k, v) -> {
newDocument.append(k, v);
});
// append this to the collection - this is where I am confused
// for this example just hardcoding the _id value for simplicity
collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));
However when I do a System.out.println(collection.find().first())
in the code after this or db.collection-name.find.pretty()
in a mongo session the new document has not been added. There are no errors thrown and completes fine.
What I am wondering is
- Is the line
collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));
correct? - Has it been added but not been saved - if so how do I save?
- Can I do this at a document level, for example
document.update(new Documen(Updates.push("calculations", newDocument));
or similar? - I have also tried
collection.findAndUpdateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));
with the same result - Is how I am getting/hardcoding the document ID incorrect?