db.User.aggregate(
[
// First step is to extract the "friends" field to work with the values
{
$unwind: "$friends"
},
// Lookup all the linked friends from the User collection
{
$lookup:
{
from: "User",
localField: "friends",
foreignField: "_id",
as: "friendsData"
}
},
// Sort the results by age
{
$sort: { 'friendsData.age': 1 }
},
// Get the results into a single array
{
$unwind: "$friendsData"
},
// Group the friends by user id
{
$group:
{
_id: "$_id",
friends: { $push: "$friends" },
friendsData: { $push: "$friendsData" }
}
}
]
)
编辑:此答案仅适用于v3.2之前的MongoDb版本。
你不能只在一个查询中做你想做的事。您必须首先检索朋友用户id的列表,然后将这些id传递给第二个查询以检索文档并按年龄对其进行排序。
https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/
这是mongodb中连接查询的文档,这是版本3.2的新特性。
所以这会有帮助的。
要使用聚合框架的$lookup功能只使用一个查询获得所有内容,请尝试以下操作:
假设您的用户集合的内容如下:
查询结果为:
相关问题 更多 >
编程相关推荐