【问题标题】:MongoDB match in aggregation lookup聚合查找中的 MongoDB 匹配
【发布时间】:2022-06-16 17:04:56
【问题描述】:

这是我当前的查询:

db.ministryteams.aggregate([
    {
        $addFields: {
            "id_ministryTeam": { $toObjectId: "$_id" }
        }
    },
    {
        $lookup:
        {
            from: "profiles",
            localField: "phone",
            foreignField: "phone",
            as: "profile"
        },
    },
    { $unwind: "$profile" },
    {
        $project: {
            "profile._id": 1,
            "profile.name": 1,
            "profile.phone": 1,
            "profile.type": 1,
            "profile.contactAllowed": 1,
            "profile.createAt": 1,
            "id_ministryTeam": 1,
            "_id": 0
        }
    }
])

目前此查询返回两个配置文件:

[{
  "id_ministryTeam": "ObjectId(\"62a79c461df25412ae7ef2ff\")",
  "profile": {
    "_id": "ObjectId(\"62a798074e105c2b74fe6d81\")",
    "name": "Informe seu nome aqui.",
    "contactAllowed": true,
    "type": "member",
    "phone": "16900001111"
  }
},
{
  "id_ministryTeam": "ObjectId(\"62a79cf21df25412ae7ef311\")",
  "profile": {
    "_id": "ObjectId(\"62a79cf21df25412ae7ef30e\")",
    "name": "Informe seu nome aqui.",
    "contactAllowed": true,
    "type": "member",
    "phone": "16900001112"
  }
}]

我只想带一个结果,profile._id: "62a798074e105c2b74fe6d81",我在比赛中尝试了几次,但我无法得到预期的结果,如果有人可以帮助我的话。

【问题讨论】:

  • 在$project 阶段之前添加一个$match 阶段以匹配profile._id,第二个选项可以避免$unwind 阶段,而您可以使用$filter 运算符直接过滤特定的配置文件ID $project舞台。

标签: mongodb


【解决方案1】:

试试这样的

db.ministryteams.aggregate([
    {
        $addFields: {
            "id_ministryTeam": { $toObjectId: "$_id" }
        }
    },
    {
        $lookup:
        {
            from: "profiles",
            localField: "phone",
            foreignField: "phone",
            as: "profile"
        },
    },
    { $unwind: "$profile" },
    { $match: { "profile._id": mongoose.Types.ObjectId("your_ID_here") } },
    {
        $project: {
            "profile._id": 1,
            "profile.name": 1,
            "profile.phone": 1,
            "profile.type": 1,
            "profile.contactAllowed": 1,
            "profile.createAt": 1,
            "id_ministryTeam": 1,
            "_id": 0
        }
    }
])

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2023-02-25
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多