intranis logo
Published on

Querying with MongoDB – ({"db":"mongo", "post":"Querying with MongoDB"})

Authors

Recently I have been working on MongoDB and let me tell you its a lot of fun, specially, if you are aware of JSON as MongoDB stores the data in BSON (Binary JSON) format.

MongoDB is a NoSQL database. More details on NoSQL at :http://nosql-database.org/. More specific details on MongoDB at: http://www.mongodb.org/

This post is to get you started with running a single instance of MongoDB. You can also configure MongoDB to run as a replica-set( More than 1 instances in the same machine or different machines ) where one node becomes the primary and the rest nodes, secondary. More details on ReplicaSet configuration at: https://www.mongodb.com/docs/manual/replication/.

Mongo uses Mongo Query Language to do db queries. Listed below are some of the command line queries that should get you started with MongoDB:

Starting your mongodb instance: mongod –dbpath C:\data\db

Here C:\data\db is path where mongo stores its data. It is recommended that you create a folder "db" inside a folder "data" in the drive where you have installed MongoDB before you start with MongoDB.

Connecting to your mongodb instance: mongo localhost:27017

Connecting to specific database in mongo: use <DB-NAME>

After this you may use following commands to do some basic queries:

  1. Find all documents in a collection:
    db.collection.find()

  2. Find a document with specified id:
    db.collection.find({"_id":"UPID001"}) // "_id" is a field

  3. Select a subset of fields from the result:
    db.collection.find({"_id":"UPID001"},{tpid:1})
    db.collection.find({"_id":"UPID001"},{tpid:1,childUpids:1}) // "tpid" and "childUpids" are fields which we want to fetch

  4. Find "limit" no of documents(records) and skipping the first "skip" documents:
    Syntax: db.collection.find().skip(skip).limit(limit);

  5. Find a document which has a specified value in its array field:
    e.g, To fetch the document containing "UPID002" as one of the values in array field "childUpids"
    db.collection.find({childUpids : "UPID002"});

  6. Update the value of a specified key for a given key value:
    db.collection.update({"_id":"UPID001"},{$set:{"carrier":"abc"}}) // update single key
    db.collection.update({"_id":"UPID001"},{$set:{"carrier":"xyz","weight":9}}) // update multiple fields "carrier" and "weight" at once

  7. Update an array field to add/remove a value for a given key:
    db.collection.update({"_id":"UPID001"},{$push:{"childUpids":"UPID999"}}) // adds to an existing array
    db.collection.update({"_id":"UPID001"},{$pull:{"childUpids":"UPID999"}}) // removes from an existing array

  8. Remove a document from the collection
    db.collection.remove({}); // removes all
    db.collection.remove({"tpid":"TPID001"}); // removes all where tpid == TPID001