gpt4 book ai didi

join - 如何在mongodb中加入查询?

转载 作者:IT老高 更新时间:2023-10-28 11:04:13 26 4
gpt4 key购买 nike

我有这样的用户文档集合:

User {
id:"001"
name:"John",
age:30,
friends:["userId1","userId2","userId3"....]
}

一个用户有很多 friend ,我在SQL中有如下查询:

select * from user where in (select friends from user where id=?) order by age

我想在 MongoDB 中有类似的东西。

最佳答案

要使用聚合框架的 $lookup 功能只需一个查询即可获得所有内容,请尝试以下操作:

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" }
}
}
]
)

假设您的用户集合的内容如下:

{
"_id" : ObjectId("573b09e6322304d5e7c6256e"),
"name" : "John",
"age" : 30,
"friends" : [
"userId1",
"userId2",
"userId3"
]
}
{ "_id" : "userId1", "name" : "Derek", "age" : 34 }
{ "_id" : "userId2", "name" : "Homer", "age" : 44 }
{ "_id" : "userId3", "name" : "Bobby", "age" : 12 }

查询的结果将是:

{
"_id" : ObjectId("573b09e6322304d5e7c6256e"),
"friends" : [
"userId3",
"userId1",
"userId2"
],
"friendsData" : [
{
"_id" : "userId3",
"name" : "Bobby",
"age" : 12
},
{
"_id" : "userId1",
"name" : "Derek",
"age" : 34
},
{
"_id" : "userId2",
"name" : "Homer",
"age" : 44
}
]
}

关于join - 如何在mongodb中加入查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4563205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com