问题显示如下:
我的疑问:
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"
]
}
现在我希望通过标记的显示来排序查询,即_id:3是标记字段的最匹配记录,后跟_id:2。
有人可以帮我解决这个问题吗?
答案 0 :(得分: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}}
]);