2017-06-21 30 views
0

我試圖在MongoDB中的「todos」集合中獲取所有唯一鍵。我的「todos」系列裏有4000個todos,大約需要0.5秒。這也意味着,更多的待辦事項我有這個集合中,長此功能需要。如何獲得在整個蒙戈集合中的所有唯一鍵?

有沒有更有效的方法?我的目標是提高性能。

預先感謝您。

db.collection('todos').find().forEach(function (doc) { 
    count++; 
    Object.keys(doc).forEach(function (key) { 
     allKeys.push(key); 
    }) 
    if (count == 4000) { 
     var unique = allKeys.filter((it, i, ar) => ar.indexOf(it) === i); 
     console.log(unique); 
    } 
}); 

回答

-1

此:

db.collection('todos').distinct("_id") 

幾乎肯定會更快,只要你有你的蒙戈集合的默認_id屬性。

+0

問題實際上是要求「鑰匙」而不是「價值」。它早已被回答了。 –