所以在我的数据库中,我有3个集合,它们看起来像这样:
客户:
customers = [
{_id: 1, username: "jack", ... },
{_id: 2, username: "jane", ... }
...
]
评论:
reviews = [
{ _id: 1, customerID: 1, message: "my message", ...}
...
]
评论:
comments = [
{ _id: 1, reviewID: 1, customerID: 2, message: "my response" ...}
...
]
客户可以发表评论,也可以评论其他评论。
因此,我想要的是mongodb aggregation
查询:
获取评论。
进行审核的客户的数据。
对该评论的评论。
对该评论发表评论的客户的数据。
即
reviews = [
{
_id: 1,
username: "jack",
message: "my message"
comments: [
{ _id: 1, username: "jane", message: "my response", ...},
...
]
...
}
...
]
答案 0 :(得分:1)
您可以从comments
集合开始,到$lookup以customers
来获得customer
的名称,然后可以$group通过评论查看所有评论,{{3 }}两次(使用reviews
和customer
)。每当您知道这是一对一的关系时,您可以在$lookup之后使用$unwind。试试:
db.comments.aggregate([
{
$lookup: {
from: "customers",
localField: "customerID",
foreignField: "_id",
as: "customer"
}
},
{
$unwind: "$customer"
},
{
$project: {
_id: 1,
reviewID: 1,
username: "$customer.username",
message: 1
}
},
{
$group: {
_id: "$reviewID",
comments: { $push: { _id: "$_id", username: "$username", message: "$message" } }
}
},
{
$lookup: {
from: "reviews",
localField: "_id",
foreignField: "_id",
as: "review"
}
},
{
$unwind: "$review"
},
{
$lookup: {
from: "customers",
localField: "review.customerID",
foreignField: "_id",
as: "customer"
}
},
{
$unwind: "$customer"
},
{
$project: {
_id: 1,
message: "$review.message",
username: "$customer.username",
comments: 1
}
}
])
输出:
{ "_id" : 1, "comments" : [ { "_id" : 1, "username" : "jane", "message" : "my response" } ], "message" : "my message", "username" : "jack" }
编辑:
如果您想从reviews
开始并将其过滤为单个电影,则可以使用$lookup
db.reviews.aggregate([
{
$match: {
movieId: 1,
}
},
{
$lookup: {
from: "customers",
localField: "customerID",
foreignField: "_id",
as: "customer"
}
},
{
$unwind: "$customer"
},
{
$lookup: {
from: "comments",
let: { reviewId: "$_id" },
pipeline: [
{
$match: { $expr: { $eq: [ "$$reviewId", "$reviewID" ] } }
},
{
$lookup: {
from: "customers",
localField: "customerID",
foreignField: "_id",
as: "customer"
}
},
{
$unwind: "$customer"
},
{
$project: {
_id: 1,
message: 1,
username: "$customer.username"
}
}
],
as: "comments"
}
},
{
$project: {
_id: 1,
message: 1,
username: "$customer.username",
comments: 1
}
}
])
带来相同的输出
答案 1 :(得分:1)
您可以在mongodb 3.6 及更高版本
中使用以下聚合Reviews.aggregate([
{ "$lookup": {
"from": Customers.collection.name,
"let": { "customerID": "$customerID" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$customerID"] } } }
],
"as": "customer"
}},
{ "$unwind": "$customer" },
{ "$lookup": {
"from": Comments.collection.name,
"let": { "reviewID": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$reviewID", "$$reviewID"] } } },
{ "$lookup": {
"from": Customers.collection.name,
"let": { "customerID": "$customerID" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$customerID"] } } }
],
"as": "customer"
}},
{ "$unwind": "$customer" },
],
"as": "comments"
}}
])