douguachan2879 2012-01-18 05:06
浏览 34
已采纳

Mongo - 从两个集合构建表

I am trying to replicate what would be a left join in MySql in Mongo. I have a collection named Clients and another collection name Orders.

In the clients collection is have:

client_PK, FirstName, LastName, Company

In the orders collection I have:

order_PK, client_fk, OrderDate, OrderAmount,  

So i know that can use embedded documents but for the sake of this question i am looking to use the reference model.

My question is, using these two collections how would I construct a table or object similar to a left join in mysql? I know this is a document db not a relational db but im using sql language just to give you an idea of what im trying to accomplish. In MySql it would look like this:

SELECT * FROM orders LEFT JOIN clients ON clients.client_PK = orders.client_fk

with this i could now construct a table that looked like:

FirstName | LastName | Company | OrderDate | OrderAmount

then i could repeat the rows using a while loop to display all orders and display the clients name with the order. Again i know mongo isn't a relational db but i am assuming there is a way simulate a table using two collections.

Thank you.

  • 写回答

2条回答 默认 最新

  • doujin8476 2012-01-18 16:56
    关注

    You almost certainly want to be storing these data all in the same MongoCollection (even in just a denormalization collection).

    If you absolutely can't do that, though, and if your set is small, you can do something similar to this (since you asked about PHP):

    <?php
    // gather orders
    $orders = iterator_to_array($mongodb->orders->find());
    $joinedOrders = array();
    // gather clients
    foreach ($db->clients->find() as $client) {
        // iterate orders (like a left join)
        foreach ($orders as $order) {
            // make a "joinedOrders" record for each join match
            if ($order['client_fk'] == $client['client_PK']) {
                $joinedOrders[] = array_merge($order, $client);
            }
        }
    }
    // result is now in $joinedOrders
    

    This is, however, almost always a bad idea. (-: You really should be denormalizing your data, or using a relational database to store/query relational data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?