2017-02-09 69 views
1

(問題this one啓發)發現蒙戈文件而忽略重複值MONGO側

給定數據集:

db.mycollection.insert([ 
    {a:1, b:2, c:3}, 
    {a:1, b:3, c:4}, 
    {a:0, b:1, c:3}, 
    {a:3, b:2, c:4} 
    {a:4, b:1, c:4} 
]) 

我想找到一個關鍵的給定值(說應該介於0和3包括)一個和只有一個文檔,並忽略該值的後續查找,即如果已找到a值爲1的文檔,則搜索不應返回任何文檔,並將1作爲a鍵的值了。調查結果的順序可以由另一個鍵的值決定。

在我們的例子中,預計產量將是:

# Findings are sorted by value of the b key 
[{a:0, b:1, c:3}, {a:3, b:2, c:4}, {a:1, b:2, c:3}] 

這裏是我工作的代碼,我只好再從我的身邊,而不是蒙戈側掉落副本。

import pymongo, pandas 

result = dict(db.mycollection.find({'a': {'$in': [i for i in range(4)]}}).sort('b', pymongo.ASCENDING)) 

print(result) 
>>> [{a:0, b:1, c:3}, {a:3, b:2, c:4}, {a:1, b:2, c:3}, {a:1, b:3, c:4}] 

因爲我有收集可能含有數以百萬計的文檔工作,我需要的「忽略重複」要在蒙戈端完成的一部分,既節省內存和數據傳輸時間。

+1

對鍵b進行排序,然後按a鍵選擇組合。 – Veeram

回答

0

從Veeram評論:

l = [i for i in range(4)] 

result = db.mycollection.aggregate([{'$sort': {'b': 1}}, 
          {'$group': { 
           '_id': '$a', 
           'data': {'$first': '$$ROOT'} 
             } 
          }, 
          {'$match': {'_id': {'$in': l}}}]) 

result_list = [i['data'] for i in result] 

print(result_list) # Omitted the ObjectId that should appear too 
>>>[{'a': 3, 'b': 2, 'c': 4}, 
    {'a': 1, 'b': 2, 'c': 3}, 
    {'a': 0, 'b': 1, 'c': 3}] 

這似乎爲我工作,你只需要注意你的結果不一定會由「B」鍵來分類的,因爲它遍歷的「a '鍵,然後再看'b'的順序。