Random   •   Archives   •   RSS   •   About   •   Contact

Control a MongoDB collection in configuration management

This post explains how to use configuration management (Salt Stack) to completely control a MongoDB collection. In our example we want to control a store's collection of plans.

First we create a JSON representation of the collection.


  "_id" : { "$oid" : "4ef8b9e2be329f491d98f74b" },
  "cost" : 20, "description" : "development",
  "name" : "good", "count" : 6000
  "_id" : { "$oid" : "4ef8b9e8be329f491d98f74c" },
  "cost" : 60, "description" : "freelancers",
  "name" : "better", "count" : 36000
  "_id" : { "$oid" : "4ef8b9f0be329f491d98f74d" },
  "cost" : 180, "description" : "production",
  "name" : "best", "count" : 162000

Next we configure a salt state formula to manage the JSON file and watch it for changes.


# install mongodb server
    - installed

# manage the store's plan.json
    - source: salt://mongodb/plan.json
    - user: root
    - group: root
    - mode: 644

# import the plan collection if it changes
      - name: mongoimport --db=store --collection=plan --upsert /tmp/plan.json
      - require:
        - pkg: mongodb-server
      - watch:
        - file: /tmp/plan.json

Now whenever plan.json is altered in configuration management, the file on the minion will update which will trigger a mongoimport with upsert to occur.

Optionally, we could replace --upsert with --drop which will drop the collection before re-importing thus removing stale records.

We now have a version controlled JSON file in configuration management and the power of MongoDB Document Objects in our application code!

Looking for a better comment system?

You should try Remarkbox — a hosted comment service that embeds in your pages to keep the conversation in the same place as your content. It works everywhere, even static sites!

Remarks: Control a MongoDB collection in configuration management

© Russell Ballestrini.