gpt4 book ai didi

javascript - MongoDB 聚合 $lookup $match

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:48 25 4
gpt4 key购买 nike

我的连接集合有一个名为authors的ObjectId数组字段。我想连接作者数组中的所有名字和姓氏。现在我从集合中的所有用户那里获取名字。无法使 $match 聚合工作。谢谢!

连接架构

const connectionSchema = new mongoose.Schema({
authors: [{ type: mongoose.Schema.Types.ObjectId, required: true }],
messages: [messageSchema]
});

代码有问题

   const connections = await Connection.aggregate([

{
$lookup: {
from: "users",
let: { users: "users" },
pipeline: [
{ $match: { _id: { $in: ["_id", "$authors"] } } },
{
$project: {
name: {
$concat: ["$firstname", " ", "$lastname"]
}
}
}
],
as: "userName"
}
},

最佳答案

您在connection架构中有authors字段。因此,请在 let 变量中使用 authors 来在 users 管道中使用 { "$in": ["$_id ", "$$authors"] }

const connections = await Connection.aggregate([
{
"$lookup": {
"from": "users",
"let": { "authors": "$authors" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$_id", "$$authors"] } } },
{
"$project": {
"name": {
"$concat": ["$firstname", " ", "$lastname"]
}
}
}
],
"as": "userName"
}
}
])

关于javascript - MongoDB 聚合 $lookup $match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com