Reputation: 15032
Edit ========================
Suppose you have 10 documents in your collection, and you want to reserve random document in it, so that no other request could also use it, for that purpose I'm using atomic $set and field "taken", after the document is set "taken" to true it is no longer participates in query, so it can't get used by any other request to database, the only problem is that after it is "taken" I don't know how to get the document that just had been updated.
Edit ========================
I'm having difficulty with obtaining a document that was just modified.
Example:
Sample documents:
{"_id":"a...", "age":23, "taken": false}
{"_id":"b...", "age":25, "taken": true},
{"_id":"c...", "age":27, "taken": false},
{"_id":"d...", "age":27, "taken": true},
{"_id":"e...", "age":29, "taken": false},
{"_id":"f...", "age":29, "taken": false}
The code:
collection.Update(Query.And(Query.GTE("age", 26), Query.EQ("taken", false)), Update.Set("taken", true));
I need a way to get the record that was "taken", is there a way to do that?
Thank you,
Upvotes: 0
Views: 1928
Reputation: 861
You can use the 'FindAndModify' method, which updates a single document, and then returns that document.
var query = Query.And(Query.GTE("age", 26), Query.EQ("taken", false));
var update = Update.Set("taken", true);
var result = collection.FindAndModify(
query,
update,
true // return new document
);
var chosenDoc = result.ModifiedDocument;
The C# documentation is here, and the general information on findAndModify is here.
Upvotes: 3
Reputation: 15032
C# driver has a method "FindAndModify" it can return last updated document
Upvotes: 2