Some mongodb commands
Here are 3 basic steps for beginners of mongodb:- starting mongodb service:
entersudo service mongod start
on the terminal - launching the mongodb:
mongo
to start the db - create a database:
use
+[the name of the database]
and you can check the creation with commanddb
- create a collection:
db.createCollection(
+[the name of the collection]+)
to create a collection
the collection can be check withshow collections
- insert data into
collection:db.COLLECTION_NAME.insert(document)
note that document should be json formatted - retrieving data:
db.COLLECTION_NAME.find()
data can be formatted withdb.COLLECTION_NAME.find().pretty()
- starting mongodb service:
Operating Mongodb with python
First of all we need the package pymongo
New version of pymongo establish the connection to mongodb with MongoClient which can be imported withfrom pymongo import MongoClient
Insert data
Here is the complete processes of inserting data ( into a collection called red from database ‘wine_quality’ )with python:
# mongodb
client = MongoClient()
db=client.get_database("wine_quality")
for row in data:
print(row)
db.red.insert(row)
- Retrieve data
# mongodb
client = MongoClient()
db = client.get_database("wine_quality")
data=db.red.find()
for row in data:
print(row)