我们可以使用$lookup 来合并同一数据库的两个不同集合中的文档,并对集合执行左外连接。
让我们下面的文件在content集合
{
"_id" : ObjectId("59ef51f106b0505f997f84c8"),
"title" : "myfavoritesong",
"description" : "A wonderful composition using string instruments"
}
{
"_id" : ObjectId("59ef52ad06b0505f997f84ca"),
"title" : "myfavoritestory",
"description" : "An interesting short story with a twisted ending"
}
viewed 集合中的文档
{
"_id" : ObjectId("59ef523706b0505f997f84c9"),
"contentid" : ObjectId("59ef51f106b0505f997f84c8"),
"viewedby" : "user1"
}
{
"_id" : ObjectId("59ef52f406b0505f997f84cb"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user2"
}
{
"_id" : ObjectId("59ef53c706b0505f997f84cc"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user3"
}
通过组合两个集合使用 $lookup 的最终聚合查询是
db.viewed.aggregate({
$lookup:{
from : "content",
localField: "contentid",
foreignField:"_id",
as:"viewed_contents"
}
})
我们的样本数据的聚合查询结果是
{
"_id" : ObjectId("59ef523706b0505f997f84c9"),
"contentid" : ObjectId("59ef51f106b0505f997f84c8"),
"viewedby" : "user1",
"viewed_contents" : [
{
"_id" : ObjectId("59ef51f106b0505f997f84c8"),
"title" : "myfavoritesong",
"description" : "A wonderful composition using string in
struments"
}
]
}
{
"_id" : ObjectId("59ef52f406b0505f997f84cb"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user2",
"viewed_contents" : [
{
"_id" : ObjectId("59ef52ad06b0505f997f84ca"),
"title" : "myfavoritestory",
"description" : "An interesting short story with a twist
ed ending"
}
]
}
{
"_id" : ObjectId("59ef53c706b0505f997f84cc"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user3",
"viewed_contents" : [
{
"_id" : ObjectId("59ef52ad06b0505f997f84ca"),
"title" : "myfavoritestory",
"description" : "An interesting short story with a twist
ed ending"
}
]
}
请注意,您还可以将 viewed 中的集合交换为外部集合,将 content 集合为本地集合
db.content.aggregate({
$lookup:{
from : "viewed",
localField: "_id",
foreignField:"contentid",
as:"contents_viewed_by"
}
})
本次聚合查询结果如下
{
"_id" : ObjectId("59ef51f106b0505f997f84c8"),
"title" : "myfavoritesong",
"description" : "A wonderful composition using string instruments",
"contents_viewed_by" : [
{
"_id" : ObjectId("59ef523706b0505f997f84c9"),
"contentid" : ObjectId("59ef51f106b0505f997f84c8"),
"viewedby" : "user1"
}
]
}
{
"_id" : ObjectId("59ef52ad06b0505f997f84ca"),
"title" : "myfavoritestory",
"description" : "An interesting short story with a twisted ending",
"contents_viewed_by" : [
{
"_id" : ObjectId("59ef52f406b0505f997f84cb"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user2"
},
{
"_id" : ObjectId("59ef53c706b0505f997f84cc"),
"contentid" : ObjectId("59ef52ad06b0505f997f84ca"),
"viewedby" : "user3"
}
]
}