Python : Dictionary comprehension

Before updating a no sql or mongo doc you need to ensure that you are not adding keys which are not part of initial doc then dictionary comprehension is really helpful.

What it means, is you are able to create a dict (json object) dynamically in single line of code using loops, condition, construction every thing together.

Single line comprehension

items_to_update = {key: value for key, value in payload.items() if key in req_items}

 

multi line interpretation

if key in req_items:

….for key, value in payload.items():

…….. dictionary[key]=value

Detailed example of created update doc dic before inserting in mongo db

try:
    req_items = ["property1","property2"]
    items_to_update = {key: value for key, value in payload.items() if key in req_items}
  
    if items_to_update:
        logger.info("Updating device collection with {}".format(items_to_update))
        self.db.update({"filter": filter}, {"$set": items_to_update}, multi=True)
        logger.info("Successfully updated product details")
except PyMongoError as e:
    logger.critical('Pymongo Exception {}'.format(str(e)))
except Exception as e:
    logger.critical('Exception {}'.format(str(e)))

 

asd

Advertisements

Mongodb – can‚Äôt login via -u root -p bitnami

Are you trying to login like this?

mongo admin --username root --password YOUR_PASSWORD

where YOUR_PASSWORD is the one you can see in your AWS system log:

Setting Bitnami application password to 'YOUR_PASSWORD'

If this doesn’t work, you can also try resetting MongoDB password:

http://wiki.bitnami.com/Components/mongoDB?highlight=mongo#How_to_reset_the_MongoDB_root_password.3f

MongoDb : Case in-sensative search using pymongo

As we all know Json is case sensitive and so is MongoDB, hence searching same name which got save in different case might not return any result. The solution is to do case in-sensative search.

Below is the example of pymongo

db.users.find_one({'name': re.compile(username, re.IGNORECASE)})

MongoDB : Java program to do basic crud operation

Sample Java program to connect MongoDb and perform Crud Operations.

Copy paste, run and learn ūüėČ

note :- Please ensure you have installed mongo dependency using jar, github or mvn

 

package com.premaseem.core;

import com.mongodb.*;

import java.util.Date;

/**
 * Java + MongoDB Crud operation example
 *
 */
public class App {
    public static void main(String[] args) {

        try {

            /**** Connect to MongoDB ****/
            // Since 2.10.0, uses MongoClient
            MongoClient mongo = new MongoClient("localhost", 27017);

            // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
//            MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
//                    new ServerAddress("localhost", 27018),
//                    new ServerAddress("localhost", 27019)));

            /**** Get database ****/
            // if database doesn't exists, MongoDB will create it for you
            DB db = mongo.getDB("testdb");

            /**** Get collection / table from 'testdb' ****/
            // if collection doesn't exists, MongoDB will create it for you
            DBCollection table = db.getCollection("user");

            /**** Insert ****/
            // create a document to store key and value
            BasicDBObject document = new BasicDBObject();
            document.put("name", "premaseem");
            document.put("age", 30);
            document.put("createdDate", new Date());
            table.insert(document);

            /**** Find and display ****/
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("name", "premaseem");

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }

            /**** Update ****/
            // search document where name="premaseem" and update it with new values
            BasicDBObject query = new BasicDBObject();
            query.put("name", "premaseem");

            BasicDBObject newDocument = new BasicDBObject();
            newDocument.put("name", "premaseem-updated");

            BasicDBObject updateObj = new BasicDBObject();
            updateObj.put("$set", newDocument);

            table.update(query, updateObj);

            /**** Find and display ****/
            BasicDBObject searchQuery2
                    = new BasicDBObject().append("name", "premaseem-updated");

            DBCursor cursor2 = table.find(searchQuery2);

            while (cursor2.hasNext()) {
                System.out.println(cursor2.next());
            }

            /**** Done ****/
            System.out.println("Done");

        }  catch (MongoException e) {
            e.printStackTrace();
        }

    }
}

MongoDB : Exporting JSON with mongoexport

This will export a JSON representation of the database. Note that as a rule – particularly for backing up or moving data – MongoDB recommends the “dump and restore” approach as BSON can contain more rich data than JSON. Nevertheless, mongoexport still has its uses, sometimes a JSON representation of the data is very useful – it’s what we’ve been using so far in the application development.

Basic output to console

Need to specify the name of the database –db and the collection –collection to export. Restoring dumped data with MongoRestore Inserts only, no updates Exporting JSON with mongoexport

Basic output to console

> mongoexport –db meantest –collection tech

Send to a file

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json

Create as array

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray

Make output pretty

> mongoexport –db meantest –collection tech –out MEAN/api/data/tech.json –jsonArray –pretty

 

MongoDB : How to take export a database using mongo dump

We need to take database backup or have to export specific database in  mongo

This command will export specific databases in mongo and export to home folder /dump

> mongodump –db testDatabase

# to compress in zip file and folder

> mongodump –db testDatabase ¬† –gzip

cd ~/dump

 

 

This command will restore or import specific db

>mongorestore –db testDatabase ¬† –gzip ¬†~/dump/testDatabase

 

With auth you can take dump as

mongodump -h 10.10.10.10¬†-p 27017 -d dbName -u “user” -p “password” –excludeCollectionsWithPrefix=system

and restore as

mongorestore -d dbName¬†–dir=dbDir

Note :

There command should be run from command prompt / shell and not from mongo sheel.

Mongo restroe does not update existing collections