0
比方說,我想要創建一個活動源並且我有多個集合。所以我有一個Posts
和Likes
集合,我想從這兩個集合中獲取所有值並按日期對它們進行排序並返回它們。有沒有辦法查詢多個集合,而無需在MongoDb中加入它們?查詢多個集合並對輸出進行排序
比方說,我想要創建一個活動源並且我有多個集合。所以我有一個Posts
和Likes
集合,我想從這兩個集合中獲取所有值並按日期對它們進行排序並返回它們。有沒有辦法查詢多個集合,而無需在MongoDb中加入它們?查詢多個集合並對輸出進行排序
如果您願意進行永久數據庫更改,則可以使用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
}