【问题标题】:How to get the count of foreign field in mongodb using $lookup?如何使用 $lookup 获取 mongodb 中外部字段的计数?
【发布时间】:2020-04-24 05:52:29
【问题描述】:

我在 1 米关系中有 2 个集合(这是一个样本,不是真实数据) 这是问题收集的数据

[
    {
        "_id":"question1",
        "text":"test test test test"
    },
    {
        "_id":"question2",
        "text":"test test test test"
    },
    {
        "_id":"question3",
        "text":"test test test test"
    },
    {
        "_id":"question4",
        "text":"test test test test"
    }
]

这里是回复收集的数据

[
    {
        "_id":'reply1',
        "questionId":"question1",
        "text":"Hello World1"
    },

    {
        "_id":'reply2',
        "questionId":"question1",
        "text":"Hello World1"
    },

    {
        "_id":'reply3',
        "questionId":"question2",
        "text":"Hello World1"
    },

    {
        "_id":'reply4',
        "questionId":"question3",
        "text":"Hello World1"
    },
]

当我使用 $lookup 时,它会加入 2 个集合并给我这个结果

[
    {
        "_id":"question1",
        "text":"test test test test",
        "totalReplies":[{...},{...}]
    },
    {
        "_id":"question2",
        "text":"test test test test",
        "totalReplies":[{...}]
    },
    {
        "_id":"question3",
        "text":"test test test test",
        "totalReplies":[{...}]
    },
    {
        "_id":"question4",
        "text":"test test test test",
        "totalReplies":[]
    }
]

但我需要获取外部字段的计数而不是数组包含我希望结果是这样的文档

[
    {
        "_id":"question1",
        "text":"test test test test",
        "totalReplies":2
    },
    {
        "_id":"question2",
        "text":"test test test test",
        "totalReplies":1
    },
    {
        "_id":"question3",
        "text":"test test test test",
        "totalReplies":1
    },
    {
        "_id":"question4",
        "text":"test test test test",
        "totalReplies":0
    }
]

有没有办法这样做?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    你可以使用$size:

    db.collection.aggregate([
        // your current pipeline ($lookup)
        {
            $addFields: { totalReplies: { $size: "$totalReplies" } }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2020-05-26
      • 2019-02-25
      • 1970-01-01
      • 2019-02-06
      • 2021-11-09
      相关资源
      最近更新 更多