基于聚合的多集合
Aggregation based many collection
我有 3 个表像
演员
actor_id: "1"
first_name: "Penelope"
last_name: "Guiness"
电影
film_id: "1"
title: "ABC"
Film_Actor
film_id: "1"
actor_id: "22"
我想要演员主演的电影(片名),喜欢
actor_id: "1"
title: {"ABC", "DEF", "GHI"}
在这种情况下我无法得到它,我刚刚实现的只是基于 2 个集合的聚合,如:
db.actor.aggregate ([
{
$ lookup:
{
from: 'film_actor',
localField: 'actor_id',
foreignField: 'actor_id',
as: 'film_id'
} }
])
首先,我认为您的数据模型存在问题。它看起来像一个 SQL 数据库,这不是使用 mongo.
的想法
但是如果你想这样做,你应该这样做:
db.actor.aggregate([
{
$lookup: {
from: "film_actor", // the collection you are trying to match
localField: "actor_id",
foreignField: "actor_id",
as: "film_actor"
}
},
{
$lookup: {
from: "films", // the collection you are trying to match
localField: "film_actor.film_id", // or '$film_actor.actor_id' if it does not work
foreignField: "film_id",
as: "film"
}
},
{
$group: {
_id: "$actor_id",
titles: {$push: "$film.title"}
}
}
]);
希望你觉得有用。
我有 3 个表像
演员
actor_id: "1"
first_name: "Penelope"
last_name: "Guiness"
电影
film_id: "1"
title: "ABC"
Film_Actor
film_id: "1"
actor_id: "22"
我想要演员主演的电影(片名),喜欢
actor_id: "1"
title: {"ABC", "DEF", "GHI"}
在这种情况下我无法得到它,我刚刚实现的只是基于 2 个集合的聚合,如:
db.actor.aggregate ([
{
$ lookup:
{
from: 'film_actor',
localField: 'actor_id',
foreignField: 'actor_id',
as: 'film_id'
} }
])
首先,我认为您的数据模型存在问题。它看起来像一个 SQL 数据库,这不是使用 mongo.
的想法但是如果你想这样做,你应该这样做:
db.actor.aggregate([
{
$lookup: {
from: "film_actor", // the collection you are trying to match
localField: "actor_id",
foreignField: "actor_id",
as: "film_actor"
}
},
{
$lookup: {
from: "films", // the collection you are trying to match
localField: "film_actor.film_id", // or '$film_actor.actor_id' if it does not work
foreignField: "film_id",
as: "film"
}
},
{
$group: {
_id: "$actor_id",
titles: {$push: "$film.title"}
}
}
]);
希望你觉得有用。