Reputation: 1163
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?
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
[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 '$'.'
Upvotes: 0
Views: 675
Reputation: 75964
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
}
}]
Upvotes: 2