我需要按联合收集字段对数据进行排序。我可以在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
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 '$'.'
答案 0 :(得分:1)
尝试此查询。
更改 -
$lookup
切换本地字段和外地字段。
$unwind
包含$
参考。
$sort
删除$
引用。
[{
"$match": {
"status": 1
}
}, {
"$lookup": {
"from": "user_details",
"localField": "id",
"foreignField": "uid",
"as": "userdetails"
}
}, {
"$unwind": "$userdetails"
}, {
"$sort": {
"userdetails.modifiedDate": 1
}
}]