使用 Mongo 聚合管道填充来自外部集合中 ID 数组的响应
Use Mongo aggregate pipeline to populate response from an array of IDs in an external collection
我目前正在使用 MERN 堆栈开发应用程序。
我有一个 User
模型,其中文档看起来如下所示
{
username: 'Testuser',
events: {
favorited: [ObjectId("abcdefg12345678"), ObjectId("hijklmno12345678")]
}
}
然后我有一个 Event
模型,其中文档看起来如下所示
[
{
_id: ObjectId("abcdefg12345678"),
name: 'Party One',
address: 'Party St'
},
{
_id: ObjectId("hijklmno12345678"),
name: 'Party Two',
address: 'Party Lane'
},
{
_id: ObjectId("pqrstuvw12345678"),
name: 'Party Three'
address: 'Party Town'
}
]
我想 return 一个仅包含与用户文档中的 favorited
数组相对应的事件文档的数组,我只想 return 事件 name
,而不是 address
.
我想我需要使用 $lookup
和 $project
但到目前为止我的尝试都没有成功。
我最近的尝试看起来像这样。
User.aggregate([
{
$lookup: {
from: "Event",
localField: "events.favorited",
foreignField: "name",
as: "favorite_events"
}
},
{
$project: {
id: 1,
name: 1,
}
}
])
- 已更新以将 favorited 数组从 strings 更改为 ObjectIds
修复:
from
写下您在数据库中的实际 collection 姓名
foreignField
传递 _id
以将此字段与 events.favorited
匹配
as
到 return 事件在 events.favorited
领域
$project
从事件中排除 address
字段 events.favorited.address
User.aggregate([
{
$lookup: {
from: "events", // correct with yours collection name
localField: "events.favorited",
foreignField: "_id",
as: "events.favorited"
}
},
{ $project: { "events.favorited.address": 0 } }
])
我目前正在使用 MERN 堆栈开发应用程序。
我有一个 User
模型,其中文档看起来如下所示
{
username: 'Testuser',
events: {
favorited: [ObjectId("abcdefg12345678"), ObjectId("hijklmno12345678")]
}
}
然后我有一个 Event
模型,其中文档看起来如下所示
[
{
_id: ObjectId("abcdefg12345678"),
name: 'Party One',
address: 'Party St'
},
{
_id: ObjectId("hijklmno12345678"),
name: 'Party Two',
address: 'Party Lane'
},
{
_id: ObjectId("pqrstuvw12345678"),
name: 'Party Three'
address: 'Party Town'
}
]
我想 return 一个仅包含与用户文档中的 favorited
数组相对应的事件文档的数组,我只想 return 事件 name
,而不是 address
.
我想我需要使用 $lookup
和 $project
但到目前为止我的尝试都没有成功。
我最近的尝试看起来像这样。
User.aggregate([
{
$lookup: {
from: "Event",
localField: "events.favorited",
foreignField: "name",
as: "favorite_events"
}
},
{
$project: {
id: 1,
name: 1,
}
}
])
- 已更新以将 favorited 数组从 strings 更改为 ObjectIds
修复:
from
写下您在数据库中的实际 collection 姓名foreignField
传递_id
以将此字段与events.favorited
匹配
as
到 return 事件在events.favorited
领域$project
从事件中排除address
字段events.favorited.address
User.aggregate([
{
$lookup: {
from: "events", // correct with yours collection name
localField: "events.favorited",
foreignField: "_id",
as: "events.favorited"
}
},
{ $project: { "events.favorited.address": 0 } }
])