使用id搜索和按对象搜索搜索最新记录

时间:2015-02-19 11:03:56

标签: python mongodb pymongo

我刚开始使用mongodb。

我像这样插入db:

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)

现在假设数据库的状态如下:

{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'}

在进行搜索时,我做到了,

def getEntityBySearch(self, search):
    collect = self.collection.find(search)
    return collect

record = {"author":"Sanjeev"}      
fetchedData = obj.getEntityBySearch(record);    
for data in fetchedData:
    print data

结果:

Fetched entity : 
{u'_id': ObjectId('54e5bd459f937b1549022d36'), u'author': u'Sanjeev'}

再次

Fetched entity : 
{u'_id': ObjectId('54e5bd5d9f937b1549022d37'), u'author': u'Sanjeev'}

不知道这是搜索与否的最佳方式。

现在我想做的是:

  1. 按ID获取实体
  2. 按对象获取实体
  3. 获取最新实体。 (就像Sanjeev有多个记录,当我搜索时,不知道哪个记录即将发布,所以我想要最近的Sanjeev插入记录)
  4. 非常感谢帮助和建议。

1 个答案:

答案 0 :(得分:2)

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