获取mongodb中匹配的子集和子集计数

时间:2016-07-31 15:25:29

标签: mongodb mongoose

我有以下文档结构

    {
    "_id" : ObjectId("578a14112acb483c1a0dce0a"),
    "professionalInterests" : [ 
        {
            "_id" : ObjectId("578a063a0068ec0c1320a1de"),
            "interestName" : "Finance and Accounting"
        }, 
        {
            "_id" : ObjectId("578a063a0068ec0c1320a1e7"), 
            "interestName" : "Journalism and Mass Media"
        }, 
        {
            "_id" : ObjectId("578a063a0068ec0c1320a1e5"),
            "interestName" : "Manufacturing Industry"
        }
    ],
    "personalInterests" : [ 
        {
            "_id" : ObjectId("578a063a0068ec0c1320a1d2"),
            "interestName" : "Music"
        }, 
        {
            "_id" : ObjectId("578a063a0068ec0c1320a1d4"),
            "interestName" : "Sports"
        }
    ]
}

我有一些像

这样的兴趣数组
var professionalInterests = [ 
            {
                "interestName" : "Finance and Accounting"
            }
];
var personalInterests  = [ 
            {
                "interestName" : "Music"
            }
];

我想检索所有文件,但按匹配的“专业兴趣”和“专业兴趣”排序。 我试过$setIntersection,但它对我不起作用。 我还尝试了$unwind$project$size,但这不是有效的解决方案。 结果文件应该包含,但排序取决于匹配的兴趣(如果与“userA”2个兴趣匹配,“userB”3个兴趣匹配,则“userB”在列表中位于“userA”之上。

{
   professionalInterests : [],//user professional interests
   personalInterests : [],//user personal interest
   matchedProfessionalInterests : [],// contain the matched professional interest
   matchedPersonalInterests : [],// contain the matched personal interest
   matchedProfessionalInterestsCount : number,
   matchedPersonalInterests : number
}

1 个答案:

答案 0 :(得分:0)

要解决您的问题,您需要使用您提到的运算符构建聚合管道。这是一个返回所需数据的查询:

db.interests.aggregate([{$project: {professionalInterests: 1,
                                personalInterests: 1,
                                matchedProfessionalInterests: {$setIntersection: [["Finance and Accounting", "Data Modeling"], "$professionalInterests.interestName"]},
                                matchedPersonalInterests: {$setIntersection: [["Music"], "$personalInterests.interestName"]}}},
                    {$project: {professionalInterests: 1,
                                personalInterests: 1,
                                matchedProfessionalInterests: 1,
                                matchedPersonalInterests: 1,
                                matchedProfessionalInterestsCount: {$size: "$matchedProfessionalInterests"},
                                matchedPersonalInterestsCount: {$size: "$matchedPersonalInterests"}}},
                    {$sort: {matchedProfessionalInterestsCount: -1, matchedPersonalInterests: -1}}]);

由于我仍然不清楚您想要订购结果的兴趣,专业或个人,我已将它们都放入$ sort阶段。您可以根据需要轻松调整$ sort。请参阅$sort操作员文档。