简体   繁体   中英

join and sort data in mongodb php

I need to sort data by joined collections field. I can do that in mysql like that:

SELECT A.name, B.address
FROM user as A
JOIN user_details as B
     ON(A.id=B.uid)
WHERE A.status=1
ORDER BY B.modifiedDate DESC

but How can i do that in MongoDB?

UPDATED

User:

id      name    status  created_at
---------------------------------------
1      Shail    1   2/16/2017 6:40
---------------------------------------
2      Paras    1   2/16/2017 5:40

UserDetails

id    address   uid modifiedDate
--------------------------------
1     Addres1   1   2/16/2017 10:40
--------------------------------
2     Addres2   2   2/16/2017 10:35

Expected Result:

id  name    modifiedDate
------------------------------
1   Paras   2/16/2017 10:35
------------------------------
2   Shail   2/16/2017 10:40

[UPDATE 2]

I have tried to do that in MongoDB by using Aggregate Frameworks Like that :

                 [
              {
                "$match": {
                  "status": 1
                }
              },
              {
                "$lookup": {
                  "from": "user_details",
                  "localField": "uid",
                  "foreignField": "id",
                  "as": "userdetails"
                }
              },
              {
                "$unwind": "userdetails"
              },
              {
                "$sort": {
                  "$userdetails.modifiedDate": 1,
                  "posts": 1
                }
              }
            ]

        **ERROR :**


        > Fatal error: Uncaught exception 'MongoResultException' with message
        > '127.0.0.1:27017: FieldPath field names may not start with '$'.' 

Try this query.

Changes -

$lookup to switch the local field and foreign field.

$unwind to include $ reference.

$sort to remove the $ reference.

 [{
    "$match": {
        "status": 1
    }
 }, {
    "$lookup": {
        "from": "user_details",
        "localField": "id",
        "foreignField": "uid",
        "as": "userdetails"
    }
 }, {
    "$unwind": "$userdetails"
 }, {
    "$sort": {
        "userdetails.modifiedDate": 1
    }
 }]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM