Create Content Profile Data to MongoDB

1. Prerequire

  • Pycharm: conda install pymongo
  • MongoDB: Download and install MongoDB
  • Robo 3T: Download & install Robo 3T
  • MongoDB Installation Guide: Installation guide updating

2. Connect MongoDB

  • Import library
import pymongo
import datetime

2.1 Initial MongoDB Class

class MongoDB(object):

    def __init__(self, db):
        mongo_client = self._connect('127.0.0.1', '27017', '', '', db)  # default IP, port, user, pwd
        self.db_client = mongo_client[db]
        self.collection_test = self.db_client['test_collection'] # create a collection to MongoDB

2.2 Create Connect


  def _connect(self, host, port, user, pwd, db):
        mongo_info = self._splicing(host, port, user, pwd, db)
        mongo_client = pymongo.MongoClient(mongo_info)  # MongoClient check each parameter configure
        return mongo_client

2.3 Splicing connetion

    @staticmethod
    # with different user
    def _splicing(host, port, user, pwd, db):
        client = host + str(port)
        if user != '':
            client = user + pwd + host + str(port)
            if db != '':
                client = client + db
        return client

3. Test&Result

3.1 Content Profile

    def test_insert(self):  # content profile
        test_collection = dict()
        test_collection['name'] = 'AINLPer'
        test_collection['job'] = 'AI algorithm'
        test_collection['date'] = datetime.datetime.utcnow()
        self.collection_test.insert_one(test_collection)  # insert one

3.2 Test

if __name__ == '__main__':
    mongo = MongoDB(db='mongodbnlp')
    mongo.test_insert()

3.3 Result

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/minovophy/article/details/120218347