Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MongoDB Cookbook - Second Edition

You're reading from   MongoDB Cookbook - Second Edition Modern Database Management Made Easy

Arrow left icon
Product type Paperback
Published in Jan 2016
Publisher
ISBN-13 9781785289989
Length 370 pages
Edition 2nd Edition
Tools
Arrow right icon
Authors (2):
Arrow left icon
Amol Nayak Amol Nayak
Author Profile Icon Amol Nayak
Amol Nayak
Cyrus Dasadia Cyrus Dasadia
Author Profile Icon Cyrus Dasadia
Cyrus Dasadia
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Installing and Starting the Server 2. Command-line Operations and Indexes FREE CHAPTER 3. Programming Language Drivers 4. Administration 5. Advanced Operations 6. Monitoring and Backups 7. Deploying MongoDB on the Cloud 8. Integration with Hadoop 9. Open Source and Proprietary Tools A. Concepts for Reference Index

Implementing atomic counters in Mongo


Atomic counters are a necessity for a large number of use cases. Mongo doesn't have a built in feature for atomic counters; nevertheless, it can be easily implemented using some of its cool offerings. In fact, with the help of previously described findAndModify() command, implementing is quite simple. Refer to the previous recipe Atomic find and modify operations to know what atomic find and modify operations are in Mongo.

Getting ready

Look at the recipe Installing single node MongoDB in Chapter 1, Installing and Starting the Server and start a single instance of Mongo. That is the only prerequisite for this recipe. Start a mongo shell and connect to the started server.

How to do it…

  1. Execute the following piece of code from the mongo shell:

    > function getNextSequence(counterId) {
      return db.counters.findAndModify(
        {
          query: {_id : counterId},
          update: {$inc : {count : 1}},
          upsert: true,
          fields:{count:1, _id:0},
          new: true...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image