这是我查询的一个非常简化的版本。
使用for循环连接客户端的两个集合是否可接受/有效?
最多可以有2,000本书,这也意味着在favoriteBooksCollection中每位用户可能会有相同数量的喜爱书籍。
return favoriteBooksCollection
.find({user: current_userId})
.then(function(favorites){
var bookIds = favorites.map(function (a) {
return a.bookId
};
return BooksCollection
.find({_id : {$in: bookIds}})
.sort({timestamp: -1})
.then(function(books){
for(var i = 0; i < books.length; i++){
for(var j = 0; j < favorites.length; j++){
if(favorites[j].bookId == books[i]._id){
//'join' user's myRating to book document here
books[i].userRating = favorites[j].myRating;
};
};
};
// return books array of objects with newly added UserRating property
return books;
});
});
答案 0 :(得分:1)
在MongoDB的聚合API中,您会找到the $lookup
operator用于连接的内容:
<强> orders
强>:
{ "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3 }
<强> inventory
强>:
{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
{ "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
{ "_id" : 5, "sku" : null, description: "Incomplete" }
{ "_id" : 6 }
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
但是如果你不想要或不能使用聚合API,那么我建议你使用forEach
而不是for
,它更干净了你仍然得到索引。