2016-07-31 70 views
0

我有以下的文档结构获取子集的匹配子集,并计数MongoDB中

{ 
    "_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但它不是有效的解决方案。 导致文件应包含但排序取决于匹配的利息(如果与“用户A” 2个利益一致和“用户B” 3个利益则匹配的“用户B”是像上面列表中,则“用户A”。

{ 
    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

@AndriySimonov更新。 –

回答

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操作员文档。