问题
I am trying to create an activity feed with votes and comments. There is no relationship between the two collections.
To get the comments:
$CommentsCollection = $this->db->comments;
$options = ['sort' => ['created' => -1], 'limit' => 15];
$data = array ();
$resultComments = $CommentsCollection->find($data, $options);
To get the votes:
$VotesCollection = $this->db->votes;
$options = ['sort' => ['created' => -1], 'limit' => 15];
$data = array ();
$resultVotes = $VotesCollection->find($data, $options);
Now how do I combine these two separate, non related collection results and order them by created (date).
I don't think aggregation or lookup is the right method because these two tables are not related. I just want to combine the results and order them by date so I can loop through and display them on the activity feed.
回答1:
Without intermediate collection, there are two ways.
You can use
unionWithfrom version 4.4 - ReferenceBut I don't recommend if your collections are huge.
You should combine at backend. Make two http requests and sort the result. Since you get 30 records, it would be pretty fast at backend.
回答2:
What I did was use:
$finalArray = array_merge($resultComments, $resultVotes);
to merge the results. Then to sort by date did:
usort($finalArray, function($a, $b) {
return strtotime($a['created']) - strtotime($b['created']);
});
I was way overthinking it.
来源:https://stackoverflow.com/questions/62614520/two-separate-mongodb-collections-combine-the-results-to-loop-through-with-no-rel