2016-09-26 47 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

好的解决方案以及 –