Two separate MongoDB collections combine the results to loop through with no relationship

只谈情不闲聊 提交于 2021-02-11 18:23:19

问题


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.

  1. You can use unionWith from version 4.4 - Reference

    But I don't recommend if your collections are huge.

  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!