【问题标题】:Return array of first matches by field value按字段值返回第一个匹配的数组
【发布时间】:2017-01-10 20:10:47
【问题描述】:

例如,我有以下类型的集合:

[
    { batch: false, type: '' },
    { batch: false, type: '' },
    { batch: true, type: '123' },
    { batch: true, type: '123' },
    { batch: true, type: '123' },
    { batch: true, type: '234' },
    { batch: true, type: '234' },
    { batch: true, type: '234' },
    { batch: true, type: '234' },
    { batch: true, type: '567' },
    { batch: true, type: '567' }
]

所以问题是,如何返回具有{batch: false} 的对象数组,如果{batch: true} 仅返回具有相同{type} 字段的第一个对象,基本上我想得到以下响应:

[
    { batch: false, type: '' },
    { batch: false, type: '' },
    { batch: true, type: '123' },
    { batch: true, type: '234' },
    { batch: true, type: '567' }
]

【问题讨论】:

  • 我删掉了文档中的_id字段,因为我觉得这里是多余的。

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

试试下面的聚合管道

db.getCollection('yourCollection').aggregate([
    {
        $group: {
            _id: {
                k1: {
                    $cond: {
                        if: "$batch",
                        then: null,
                        else: "$_id"
                    }
                },
                k2: "$type"
            },
            batch: { $first: "$batch" },
            type: { $first: "$type" }
        }
    },
    {
        $project: {
            _id: 0,
            batch: 1,
            type: 1
        }
    }
])

导致

/* 1 */
{
    "batch" : false,
    "type" : ""
}

/* 2 */
{
    "batch" : false,
    "type" : ""
}

/* 3 */
{
    "batch" : true,
    "type" : "123"
}

/* 4 */
{
    "batch" : true,
    "type" : "567"
}

/* 5 */
{
    "batch" : true,
    "type" : "234"
}

【讨论】:

    【解决方案2】:

    运行以下聚合管道,您需要在 $group 键中有一个满足给定条件的条件:

    db.collection.aggregate([
        {
            "$group": {
                "_id": { "$cond": [ "$batch", "$type", "$_id" ] },
                "batch": { "$first": "$batch" },
                "type": { "$first": "$type" }
            }
        },
        { "$project": {  "_id": 0, "batch": 1, "type": 1  } }
    ])
    

    【讨论】:

    • 不错的答案,但是当type_id 来自同一个域时(理论上)可能存在冲突风险
    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    相关资源
    最近更新 更多