2016-09-26 43 views
0

問題說明如下:蒙戈在()子句通過最匹配的排序

我的查詢:

db.goods.find({tags:{$in:["white","black","gray"]}}).pretty(); 

和數據恢復:

{ 
    "id":1, 
    "tags": [ 
     "black", 
     "blue" 
    ] 
} 
{ 
    "id":2, 
    "tags": [ 
     "white", 
     "gray" 
    ] 
} 
{ 
    "id":3, 
    "tags": [ 
     "gray", 
     "black", 
     "white" 
    ] 
} 

現在我想通過revelence下令查詢標籤,即_id:3是標籤字段的最匹配記錄,_id:2後跟。

有人可以幫我解決這個問題嗎?

回答

1

您可以使用下面的聚集查詢來獲得期望的結果解決。

db.goods.aggregate([ 
    {$match: {tags: {$in: ["white","gray","black"]}}}, 
    {$project: {"tags":1, "tagsCopy":"$tags"}}, 
    {$unwind: "$tagsCopy"}, 
    {$match: {tagsCopy: {$in: ["white","gray","black"]}}}, 
    {$group: { 
     _id:"$_id", 
     counter:{$sum:1}, 
     tags:{"$first":"$tags"} 
    }}, 
    {$sort:{counter:-1}}, 
    {$project: {"tags":1}} 
]); 
+1

是的,這是正確的解決方案。謝謝! –

0

可以通過使用聚合

db.goods.aggregate([ 
    {$match: {tags: {$in: ["white","gray","black"]}}}, 
    {$unwind: "$tags"}, 
    {$match: {tags: {$in: ["white","gray","black"]}}}, 
    {$group: { 
     _id:"$_id", 
     matches:{$sum:1}, 
     tags: {$push:"$tags"} 
    }}, 
    {$sort:{matches:-1}} 
]); 
+0

好的解決方案以及 –