[JAVA-642] Using findAndModify to do a "getOrCreate" Created: 13/Sep/12 Updated: 11/Sep/19 Resolved: 13/Sep/12 |
|
| Status: | Closed |
| Project: | Java Driver |
| Component/s: | API |
| Affects Version/s: | 2.8.0 |
| Fix Version/s: | None |
| Type: | Task | Priority: | Minor - P4 |
| Reporter: | Michael Champagne | Assignee: | Unassigned |
| Resolution: | Done | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Environment: |
Windows |
||
| Description |
|
I would like to use findAndModify to get one document, without doing any modification on it. My need is to find a single document in a collection, or create it if it doesn't exist. Here's my java code (based on http://api.mongodb.org/java/2.8.0/) and the error I get.
Now let's take a look at the parameters : I have 2 servers that might access this database, so that's why I need an atomic-like "getOrCreate" behavior. There might be a better way of doing this. |
| Comments |
| Comment by Michael Champagne [ 14/Sep/12 ] | |
|
Didn't know that we can't update the _id field of a document.
I know this isn't the better implementation, but it's temporary until I turn all sql tables into mongo collections. I'm pretty sure it will work for my needs for now. | |
| Comment by Jeffrey Yemin [ 14/Sep/12 ] | |
|
I don't see a way around this. The _id field is immutable once the document is created, and mongo will not generate _id's other than ObjectId's Can you store the ObjectId as a binary field in your SQL database? | |
| Comment by Michael Champagne [ 14/Sep/12 ] | |
|
I have another problem with findAndModify. I don't use the ID in my query, thus when the document isn't found, it is created with a mongo generated id. I don't want to use mongo generated ids because I need a numeric value (to put in the column of a SQL table). In my java application, I am generating an ID (which is a long) and I would like the document to have that ID when not found when using findAndModify. If I can't do that, I will have to do an update after findAndModify and that will be a problem when 2 servers will run that code at the same time. The first will create the document with a mongo id, then the other might get the document with that wrong id before the first server updates it. | |
| Comment by Jeffrey Yemin [ 14/Sep/12 ] | |
|
Yeah, it's not the most intuitive API. | |
| Comment by Michael Champagne [ 14/Sep/12 ] | |
|
Thank you, it works! | |
| Comment by Jeffrey Yemin [ 13/Sep/12 ] | |
|
It's because you're passing null to the update argument (3rd from the end). Try something like:
|