-2

My data in mongoDb is stored as following:

 {
    '_id': ObjectId('59f1989a83add71bf5ae6867'), 
    'data': [              
        {'name1': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 
        'name2': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 
        'name3': 'searchValue'},
        {'name1': {'key1': 'val4', 'key2': 'val5', 'key3': 'val6'}, 
        'name2': {'key1': 'val4', 'key2': 'val5', 'key3': 'val6'}, 
        'name3': 'otherValue'},
     .
     .
     .
     ]
    }

And my query in python is

cursor = db.database.find({ "data.name3": "searchValue" }).sort([( "_id" , -1 ) ]).limit(1)

Above query returns whole data. I need following output.

{
    '_id': ObjectId('59f1989a83add71bf5ae6867'), 
    'data': [              
        {'name1': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 
        'name2': {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, 
        'name3': 'searchValue'}
    ]
}

Please help me. Thanks in advance

Anuj Shah
  • 147
  • 1
  • 9

1 Answers1

1

Can you try this :

cursor = db.database.find({ "data.name3": "searchValue" }, {"data.$" : 1}).sort([( "_id" , -1 ) ]).limit(1)
Pubudu Jayawardana
  • 2,250
  • 1
  • 13
  • 18
  • Its working. I need extra help as well. My there are other fields other than data array in my record. This query doesn't show those fields. Can you help me with that please? – Anuj Shah Oct 26 '17 at 18:16
  • 1
    You can add them into the projection options: Ex: ```cursor = db.database.find({ "data.name3": "searchValue" }, {"data.$" : 1, "other_filed_x" : 1, "other_filed_y" : 1}).sort([( "_id" , -1 ) ]).limit(1)``` – Pubudu Jayawardana Oct 26 '17 at 18:17