![](/img/trans.png)
[英]MongoDB - How to retrieve multiple collections from an array of objects that have their IDs
[英]How to quickly retrieve large array from MongoDB
我在MongoDB集合中有一個500kb的文檔,看起來像這樣,“內容”數組有5000個條目:
{
"BookID": "120",
"Content": ["The day was pretty good", .42],
["The day was great!", .83],
.....
}
使用Express從Node運行查詢花費的時間太長:500-5000ms
app.get('/sentences', function (req, res) {
start = Date.now();
db.collection('Sentences').find({ "BookID": "120"}).toArray(function (findErr, result) {
if (findErr) throw findErr;
console.log(Date.now() - start);
res.send(result[0]);
});
}
是否有適當的方法來存儲或查詢這樣的數據並獲得更快的查詢時間,還是我應該使用MongoDB以外的其他方式? 最終,我希望存儲成千上萬這樣的書,而無需進行復雜的查詢。
使用提示來提高查詢性能。
app.get('/sentences/:id', function (req, res) {
var bookID=req.params.id
start = Date.now();
db.collection('Sentences')
.find()
.hint("BookID_"+bookID)
.toArray(function (findErr, result) {
if (findErr) throw findErr;
console.log(Date.now() - start);
res.send(result[0]);
});
}
我認為您已經為集合建立了索引(如果不是,請執行此操作。這樣做會使它更快),但查詢仍然很慢。
由於這是直接獲取數據的查詢(甚至不是復雜的搜索),因此使用傳統方法很難使其更快。 但是根據您的用例,您可以使其更快,
就像使用Redis緩存結果一樣。
如果您不打算在輸出文檔上執行任何添加,更新,刪除命令,請在查詢中使用lean()。 使用lean將以javascript提供輸出,並且所有mongoose命令都不能在結果文檔上使用。 http://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/
db.collection('Sentences').find({ "BookID": "120"}).lean().toArray(function (findErr, result) {
if (findErr) throw findErr;
console.log(Date.now() - start);
res.send(result[0]);
});
我最終將數據作為JSON文件存儲在S3中。 更快更便宜
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.