Reputation: 91
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.
Upvotes: 0
Views: 2357
Reputation: 20824
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:
findOneAndUpdate
- https://docs.mongodb.com/v3.2/reference/method/db.collection.findOneAndUpdate/update
- https://docs.mongodb.com/v3.2/reference/method/db.collection.update/updateOne
- https://docs.mongodb.com/v3.2/reference/method/db.collection.updateOne/updateMany
- https://docs.mongodb.com/v3.2/reference/method/db.collection.updateMany/Refer also to What's the difference between findAndModify and update in MongoDB?
Upvotes: 1