2016-07-31 36 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操作員文檔。