如何在MongoDB的数组字段中获得项目组合? [英] how to get combinations of items in an array field in MongoDB?

查看:55
本文介绍了如何在MongoDB的数组字段中获得项目组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{_id:111,
keywords:['cs','ee','se']
},

{_id:112,
keywords:['cs','se','dd']
},

如何获得关键字项目的关系?像这样的

how can I get the relationship of keywords item? like that:

{item1:'cs',item2:'ee',count:1},
{item1:'cs',item2:'se',count:2},
{item1:'ee',item2:'se',count:1},
{item1:'cs',item2:'dd',count:1},
{item1:'se',item2:'dd',count:1},


推荐答案

如果我正确理解了您与给定示例之间的关系,则此查询应为您的问题的解决方案:

If I understood correctly you relation from given example - this query should be a solution to your problem:

db.collection.aggregate([{
            $unwind : "$keywords"
        }, {
            $lookup : {
                from : "collection",
                localField : "_id",
                foreignField : "_id",
                as : "items"
            }
        }, {
            $unwind : "$items"
        }, {
            $unwind : "$items.keywords"
        }, {
            $redact : {
                $cond : {
                    if  : {
                        $cmp : ["$keywords", "$items.keywords"]
                    },
                then : "$$DESCEND",
                else  : "$$PRUNE"
            }
        }
    }, {
        $group : {
            _id : {
                k1 : "$keywords",
                k2 : "$items.keywords",
            },
            items : {
                $sum : 0.5
            }
        }
    }, {
        $sort : {
            "_id" : 1
        }
    }, {
        $project : {
            _id : 1,
            items : 1,
            a : {
                $cond : {
                    if  : {
                        $eq : [{
                                $cmp : ["$_id.k1", "$_id.k2"]
                            }, 1]
                    },
                then : "$_id.k2",
                else  : "$_id.k1"
            }
        },
        b : {
            $cond : {
                if  : {
                    $eq : [{
                            $cmp : ["$_id.k1", "$_id.k2"]
                        }, -1]
                },
            then : "$_id.k2",
            else  : "$_id.k1"
        }
    },

}
}, {
    $group : {
        _id : {
            k1 : "$a",
            k2 : "$b",
        },
        items : {
            $sum : "$items"
        }
    }
}, {
    $project : {
        _id : 0,
        item1 : "$_id.k1",
        item2 : "$_id.k2",
        count : "$items"
    }
}
])








输出

output



{
    "item1" : "cs",
    "item2" : "dd",
    "count" : 1.0
}
{
    "item1" : "cs",
    "item2" : "ee",
    "count" : 1.0
}
{
    "item1" : "cs",
    "item2" : "se",
    "count" : 2.0
}
{
    "item1" : "dd",
    "item2" : "se",
    "count" : 1.0
}
{
    "item1" : "ee",
    "item2" : "se",
    "count" : 1.0
}

这篇关于如何在MongoDB的数组字段中获得项目组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆