![](/img/trans.png)
[英]mongodb - aggregation with $match $in with a $lookup pipeline
[英]MongoDB Aggregation $lookup $match
我的 Connection 集合具有名为 author 的 ObjectId Array 字段。 我想连接作者数组中的所有名字和姓氏。现在我从集合中的所有用户那里得到名字。 无法让 $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"
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.