查询多个集合并对输出进行排序

时间:2017-05-13 16:55:28

标签: mongodb

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

1 个答案:

答案 0 :(得分: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
}