我正在使用MongoDB Aggregation $ lookup来查询两个不同的架构集合。
我想要做的是返回已添加到每个艺术家集合中的所有用户。
这是艺术家模式
{
"_id" : ObjectId("59f7a13163241a5c8a580832"),
"artistID" : "34657839393",
"artistName" : "Mc squared",
"userID" : ObjectId("599f14855e9fcf95d0fe11a7"),
"__v" : 0
}
Artist.aggregate([
{
$match: { artistID }
},
{
$lookup: {
from: "users",
localField: "userID",
foreignField: "_id",
as: "UsersWithMatchedArtist"
}
},
{
$project: {
UsersWithMatchedArtist: 1
}
}
}
])
这将返回以下数据结构。
[
{
"_id": "59f8f40686f2fa623d815256",
"UsersWithMatchedArtist": [{Users Schema}]
},
{
"_id": "59f8f40686f2f12345678901",
"UsersWithMatchedArtist": [{Users Schema}}]
}
]
我希望在以下结构中返回数据
[
{Users Schema},
{Users Schema}
]
有关如何执行此操作的任何建议?建议将不胜感激!干杯!
答案 0 :(得分:1)
我在下面使用此查询后获得了数据集:
Artist.aggregate([
{
$match: { artistID }
},
{
$lookup: {
from: "users",
localField: "userID",
foreignField: "_id",
as: "UsersWithMatchedArtist"
}
},
{
$project: {
user: {
$arrayElemAt: ["$UsersWithMatchedArtist", 0]
}
}
},
{
$replaceRoot: {
newRoot: "$user"
}
}
])
这将返回数据集
[
{Users Schema},
{Users Schema}
]