gpt4 book ai didi

嵌入式集合的 MongoDB $lookup

转载 作者:行者123 更新时间:2023-12-04 10:18:01 24 4
gpt4 key购买 nike

我有 2 个集合:

用户集合:

[
{
"_id" : ObjectId("3a9ccf7de6348936d88b3601"),
"first_name" : "John",
},
{
"_id" : ObjectId("3a9ccf7de6348936d88b3602"),
"first_name" : "Jane",
}
]

CommentCollection(带有嵌入式 ReplyCollection):
[
{
"_id" : ObjectId("3a9ccf7de6348936d88b3601"),
"user_id": ObjectId("3a9ccf7de6348936d88b3601"),
"body" : "Hello World",
"replies":
[
{
"_id" : ObjectId("3a9ccf7de6348936d88b3441"),
"user_id": ObjectId("3a9ccf7de6348936d88b3601"),
"body" : "World said, Hello Back",
}
]
},
{
"_id" : ObjectId("3a9ccf7de6348936d88b3602"),
"user_id": ObjectId("3a9ccf7de6348936d88b3601"),
"body" : "Hello Stack",
"replies":
[
{
"_id" : ObjectId("3a9ccf7de6348936d88b3602"),
"body" : "Stack said Overflow",
"user_id": ObjectId("3a9ccf7de6348936d88b3601"),
}
]
}
]

查询加入评论和用户:
db.comments.aggregate([
{ "$lookup": {
"from": "Users",
"localField": "user_id",
"foreignField": "_id",
"as": "user" }
},
{"$unwind": "$user"}
]);

行为 : 评论和用户表按预期加入。

问题 : 是否可以在同一个查询中加入回复用户关系?

提前谢谢。

最佳答案

是的,您可以使用 uncorrelated-subquery 来做到这一点在 $lookup :

db.comments.aggregate([
{
$lookup: {
from: "Users",
let: {
repliesUserId: "$replies.user_id",
userId: "$user_id"
},
pipeline: [
{
$match: {
$expr: {
$or: [
{ $eq: ["$_id", "$$userId"] },
{ $in: ["$_id", "$$repliesUserId"] }
]
}
}
}
],
as: "user"
}
}
]);

测试: MongoDB-Playground

关于嵌入式集合的 MongoDB $lookup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993978/

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