Reputation: 5407
I just got started with mongodb.
I am inserting into db like this:
def saveEntity(self, post):
post_json = json.dumps(post)
post_json_c = post_json.replace("\"", "'")
cnt = self.collection.find().count()
return {'oid': self.collection.insert(post), 'count': cnt }
record = {"author":"Ramesh"}
save_obj = obj.saveEntity(record)
Now suppose status of database is like this:
{u'_id': ObjectId('54e49c6f9f937b23296204cc'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e49d749f937b236a8405c4'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e49df59f937b2386d7c58e'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e49e299f937b239a9e314d'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e49e3d9f937b23a13a8ff8'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e5b6939f937b0f1a1f07ed'), u'author': u'Sanjeev'}
{u'_id': ObjectId('54e5bd059f937b152ffd0e58'), u'author': u'Menon'}
{u'_id': ObjectId('54e5bd0d9f937b15355d7e72'), u'author': u'Menon'}
{u'_id': ObjectId('54e5bd1d9f937b153f751e4d'), u'author': u'Nitin'}
{u'_id': ObjectId('54e5bd1f9f937b153f751e4e'), u'author': u'Nitin'}
{u'_id': ObjectId('54e5bd209f937b153f751e4f'), u'author': u'Nitin'}
{u'_id': ObjectId('54e5bd329f937b1549022d34'), u'author': u'Ramesh'}
{u'_id': ObjectId('54e5bd349f937b1549022d35'), u'author': u'Ramesh'}
While doing search, I did,
def getEntityBySearch(self, search):
collect = self.collection.find(search)
return collect
record = {"author":"Sanjeev"}
fetchedData = obj.getEntityBySearch(record);
for data in fetchedData:
print data
result:
Fetched entity :
{u'_id': ObjectId('54e5bd459f937b1549022d36'), u'author': u'Sanjeev'}
again
Fetched entity :
{u'_id': ObjectId('54e5bd5d9f937b1549022d37'), u'author': u'Sanjeev'}
Dont know this is best way to do search or not.
Now what I want to do is:
Help and suggestions much appreciated.
Upvotes: 0
Views: 56
Reputation: 36
You can try following options:
# Get Entity by ID/Object
from bson.objectid import ObjectID
def getEntityByID(self, id):
obj_id = ObjectID(str(id))
collect = self.collection.find({'_id':obj_id})
return collect
# Get latest entity
def getLatestEntity(self, search_json, sort_by='_id'):
collect = self.collection.find(search_json).sort([(sort_by, -1)]).limit(1)
return collect
Upvotes: 2