0

What I am trying to do is very simple but I'm not sure why it's not working. What I'm trying to do is query the database on _id, if it matches, then update a specific record in the document it found.

BasicDBObject basic = new BasicDBObject();
    basic.put("_id", id);
    FindIterable<Document> cursor = collection.find(basic);
    if(cursor == null){
        Document tableEntry = new Document();
        tableEntry.put("_id", id);
        tableEntry.put("longitude", longitude);
        tableEntry.put("latitude", latitude);
        tableEntry.put("status", status);

        collection.insertOne(tableEntry);
        closeConnection();
    }else{
        for(Document doc : cursor){
            doc.put("status", "full");
        }
    }

After running this and checking the database, it doesn't seem to update. I currently have 1 document in the database and it doesn't update that. I am using the mongo java 3.4.2 driver.

1 Answer 1

1

You're using insertOne, which will insert a new document. What you need to use a command that will update an existing document, such as findOneAndUpdate.

If you use a command like findOneAndUpdate, note that it takes two parameters. The first is a query that uniquely identifies the document you want to update. The second is an object that tells how to update the document.

For example, in that second parameter, you may want to pass something like:

BasicDBObject updatedDocument = new BasicDBObject();
updatedDocument.append("$set", new BasicDBObject().append("longitude", longitude));

Mongo provides these API calls for updates:

Refer also to What's the difference between findAndModify and update in MongoDB?

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

2 Comments

I've tried that and now it updates. But what if the initial record is not added.. would findOneAndUpdate create that record if it cannot find based on the constraint in the first parameter of that method?
I think in that case, you'd need to write some logic that essentially says: "If this record exists in the database, update it; else, create a new record and insert it"

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.