![](/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.