gpt4 book ai didi

mongodb - 如何在 mongodb 中使用 $lookup 连接多个集合

转载 作者:行者123 更新时间:2023-12-03 05:51:18 25 4
gpt4 key购买 nike

我想使用聚合 $lookup 在 MongoDB 中加入两个以上的集合。可以加入吗?给我一些例子。

这里我有三个集合:

用户:

{    
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "admin@gmail.com",
"userId" : "AD",
"userName" : "admin"
}

用户信息:

{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
}

用户角色:

{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
}

最佳答案

Mongodb 3.2及以上版本支持join功能。您可以通过聚合查询来使用联接。
您可以使用下面的示例来完成:

db.users.aggregate([

// Join with user_info table
{
$lookup:{
from: "userinfo", // other table name
localField: "userId", // name of users table field
foreignField: "userId", // name of userinfo table field
as: "user_info" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only

// Join with user_role table
{
$lookup:{
from: "userrole",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" },

// define some conditions here
{
$match:{
$and:[{"userName" : "admin"}]
}
},

// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
]);

这将给出如下结果:

{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "admin@gmail.com",
"userName" : "admin",
"userPhone" : "0000000000",
"role" : "admin"
}

希望这会对您或其他人有所帮助。

谢谢

关于mongodb - 如何在 mongodb 中使用 $lookup 连接多个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35813854/

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