1

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?
1
  • So I have added in a way of getting the document ID instead of hard coding and it works?! Either I had a typo in my ID value or removing my print statement I had for debugging has made it work. If anyone could confirm that what I have done is correct that would be good so I can marked it as answered! Commented Feb 9, 2020 at 12:58

1 Answer 1

1

You have filter condition issue (your _id is ObjectId type)

new Document("_id", ObjectId("1234567890"))`

Always make sure your documents updated correctly. Look code fagment:

UpdateResult result = collection.updateOne(filter, update);
log.info("Update with date Status : " + result.wasAcknowledged());
log.info("Nº of Record Modified : "   + result.getModifiedCount());

https://api.mongodb.com/java/3.1/com/mongodb/client/result/UpdateResult.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.