在mongodb php中加入和排序数据

时间:2017-02-16 11:54:46

标签: php mongodb mongodb-query aggregation-framework

我需要按联合收集字段对数据进行排序。我可以在mysql那样做:

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

但我怎么能在MongoDB中做到这一点?

已更新

用户:

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

预期结果:

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

[更新2]

我尝试使用Aggregate Frameworks在MongoDB中这样做:

                 [
              {
                "$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 '$'.' 

1 个答案:

答案 0 :(得分:1)

尝试此查询。

更改 -

$lookup切换本地字段和外地字段。

$unwind包含$参考。

$sort删除$引用。

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