【问题标题】:'join' MongodDB collections with a for loop?使用 for 循环“加入”MongodB 集合?
【发布时间】:2016-12-25 23:51:56
【问题描述】:

这是我的查询的一个非常简化的版本。

使用 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;

    });

});

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案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,这样更干净而且你仍然可以获得索引。

    【讨论】:

    • 感谢您的回答。我正在研究 $lookup,但看到了分片可能存在的缺点。到目前为止,我可能仍然会这样做,因为我没有分片。只是在尝试学习最佳实践。
    • @NoobSter 你对分片的看法是对的。这和forEach 是在 MongoDB 中执行连接的仅有的两种方式
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2016-10-22
    • 2019-11-18
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多