See http://api.mongodb.com/python/current/tutorial.html
For a GUI, look at: https://github.com/mongo-express/mongo-express/
REST APIs at https://docs.mongodb.com/ecosystem/tools/http-interfaces/
The default REST api is unsecure, but can be tested adding rest = True at /etc/mongodb.conf
To access the db created in this howto:
http://127.0.0.1:28017/snaps/alarms/
http://127.0.0.1:28017/snaps/alarms/?filter_name=alarm%201
----
# aptitude install mongodb python-pymongo
$ ipython
In [1]: import pymongo
In [2]: client = pymongo.MongoClient()
# or >>> client = MongoClient('localhost', 27017)
# Databases and Collections are created on-the-fly
In [3]: snapsdb = client.snaps
In [10]: client.snaps
Out[10]: Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'snaps')
In [11]: alarms = snapsdb.alarms
# To insert data in a collection, just throw a dictionary of basetypes
In [8]: post = {"name":"alarm 1","values":{"attr1":0,"attr2":['just','three','strings']}}
In [12]: s = alarms.insert_one(post)
In [13]: s.inserted_id
Out[13]: ObjectId('59ba22c0496ae3058504e362')
In [16]: snapsdb.collection_names()
Out[16]: [u'alarms']
# Find_one may be colled with filters(dict) or without them
In [19]: alarms.find_one()
Out[19]:
{u'_id': ObjectId('59ba22c0496ae3058504e362'),
u'name': u'alarm 1',
u'values': {u'attr1': 0, u'attr2': [u'just', u'three', u'strings']}}
In [20]: post = {"name":"alarm 2","values":{"attr1":4,"attr2":['just','two',]}}
In [21]: alarms.insert_one(post)
In [25]: alarms.find_one({"name":"alarm 2"})
Out[25]:
{u'_id': ObjectId('59ba2342496ae3058504e363'),
u'name': u'alarm 2',
u'values': {u'attr1': 4, u'attr2': [u'just', u'two']}}
# Regexp searches syntax is ugly, but works
In [30]: alarms.find_one({"name":{'$regex':"alarm .*"}})
Out[30]:
{u'_id': ObjectId('59ba22c0496ae3058504e362'),
u'name': u'alarm 1',
u'values': {u'attr1': 0, u'attr2': [u'just', u'three', u'strings']}}
# Find multiple values
In [31]: alarms.find({"name":{'$regex':"alarm .*"}})
Out[31]: <pymongo.cursor.Cursor at 0x7f18d00fe110>
In [32]: cursor = alarms.find({"name":{'$regex':"alarm .*"}})
In [33]: list(cursor)
Out[33]:
[{u'_id': ObjectId('59ba22c0496ae3058504e362'),
u'name': u'alarm 1',
u'values': {u'attr1': 0, u'attr2': [u'just', u'three', u'strings']}},
{u'_id': ObjectId('59ba2342496ae3058504e363'),
u'name': u'alarm 2',
u'values': {u'attr1': 4, u'attr2': [u'just', u'two']}}]
No comments:
Post a Comment