Atomic find and modify operations
In Chapter 2, Command-line Operations and Indexes, we had some recipes that explained various CRUD operations we perform in MongoDB. There was one concept that we didn't cover and it is atomically find and modify documents. Modification consists of both update and delete operations. In this recipe, we will go through the basics of MongoDB's findAndModify
operation. In the next recipe, we will use this method to implement a counter.
Getting ready
Look at the recipe Installing single node MongoDB in Chapter 1, Installing and Starting the Server and start a single instance of MongoDB. That is the only prerequisite for this recipe. Start a mongo shell and connect to the started server.
How to do it…
- We will test a document in
atomicOperationsTest
collection. Execute the following from the shell:> db.atomicOperationsTest.drop() > db.atomicOperationsTest.insert({i:1})
- Execute the following from the mongo shell and observe the output:
> db...