【问题标题】:Query multiple collections and sort on output查询多个集合并对输出进行排序
【发布时间】:2017-05-13 16:55:27
【问题描述】:

假设我想创建一个活动供稿并且我有多个集合。所以我有一个PostsLikes 集合,我想从这两个集合中获取所有值并按日期对它们进行排序并返回它们。有没有办法在不加入 MongoDb 的情况下查询多个集合?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    如果您愿意永久更改数据库,可以使用Mongodb aggregate method。 但是,您也可以使用这个:

    //This is what your final, sorted array of blog post objects will be
    var blogPosts = [];
    //Search posts collection
    db.posts.find({}, function(err, docs){
       //Sort by how long ago post was made
       posts = docs.sort(function(a,b){return a.timeAgo - b.timeAgo});
       for(var i = 0; i < posts.length; i++){
          //Add blog post to final array
          blogPosts.push({post:posts[i], likes:0});
       };
    }.exec(function(err){
       //Once executed, find likes
       db.likes.find({}, function(err, likes){
          for(var i = 0; i < likes.length; i++){
             var index = blogPosts.findIndexOf(function(post){
                //Find where in the array the postname associated with the like (I assume this is in your DB) is the name of a post
                return post.name == likes[i].post;
             });
             //Add to final array
             blogPosts[index].likes +=1
          };
       });
    });
    

    不过,如果可以的话,我建议让每个博客文章文档都有点赞数,而不是将帖子和点赞存储在单独的集合中。它会让事情变得容易得多。 您对每个数据库文档都有什么(我想):

    like: {
       by: username,
       post: blogpostname
    }
    post: {
       by: username,
       name: postname,
       timeAgo: date,
    }
    

    ...或者类似的东西。 相反,这更有效:

    post: {
       by: username,
       timeAgo: date,
       name: postname,
       likes: amountoflikes
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 2016-05-02
      相关资源
      最近更新 更多