具有排名/搜索计数的Mongodb
大家好 我花了三天时间试图找到解决方案,但都找不到。希望你们能帮我 资料 这是我到目前为止所做的查询:具有排名/搜索计数的Mongodb,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,大家好 我花了三天时间试图找到解决方案,但都找不到。希望你们能帮我 资料 这是我到目前为止所做的查询: var col = ['yellow', 'red', 'blue']; db.getCollection('data').aggregate([ { $match: { colors : { $in : col } } }, { $group: { _id: { 'item': '$item', colors: { $size : '$col
var col = ['yellow', 'red', 'blue'];
db.getCollection('data').aggregate([
{ $match: { colors : { $in : col } } },
{ $group: { _id: { 'item': '$item', colors: { $size : '$colors' } } } }
])
结果呢
{
"_id" : {
"item" : "pen-1",
"colors" : 6
}
}
{
"_id" : {
"item" : "pen-2",
"colors" : 4
}
}
我想做的是:
归还物品,
返回(颜色/匹配颜色)的总数
所以应该是这样的:
"_id" : {
"item" : "pen-1",
"rank": 0.5 // total colors(6) / that match(3)
}
"_id" : {
"item" : "pen-2",
"rank": 0.25 // total colors(4) / that match(1)
}
以下是如何从v开始在MongoDB中实现这一点。3.4:
var colors=['红色','粉色'];
db.getCollection('test').aggregate([
//筛选出颜色数组为空的记录
//避免被零除。
{
$match:{
'colors.0':{$exists:true}
}
},
{
$addFields:{
匹配颜色:{
$filter:{
输入:“$colors”,
例如:'颜色',
条件:{'$in':['$$color',colors]}
}
}
}
},
{
$项目:{
项目:“$item”,
分数:{$divide:[{$size:'$matchingColors'},{$size:'$colors'}]}
}
}
]);代码>您可以使用运算符,它接受两个或多个数组并返回一个数组,该数组包含每个输入数组中出现的元素。然后可以使用返回结果数组中的元素数,以获得匹配的总颜色
如果使用MongoDB 3.4及更新版本,则将允许您在文档中添加一个额外字段,而无需显式投影其余字段,否则就足够了
以下示例显示了这一点:
var col = ['yellow', 'red', 'blue'];
db.getCollection('data').aggregate([
{ "$match": { "colors": { "$in": col } } },
{
"$addFields": {
"rank": {
"$divide": [
{ "$size": { "$setIntersection": ["$colors", col] } },
{ "$size": "$colors" }
]
}
}
},
{ "$sort": { "rank": 1 } }
])
样本输出
/* 1 */
{
"_id" : ObjectId("58c645eaf3d1c82da16279a6"),
"item" : "pen-2",
"colors" : [
"green",
"blue",
"pink",
"purple"
],
"rank" : 0.25
}
/* 2 */
{
"_id" : ObjectId("58c645eaf3d1c82da16279a5"),
"item" : "pen-1",
"colors" : [
"yellow",
"green",
"blue",
"red",
"pink",
"purple"
],
"rank" : 0.5
}
你的MongoDB服务器版本是什么?嗨,是v3.4.2.OMg!太快了!非常感谢你:D
/* 1 */
{
"_id" : ObjectId("58c645eaf3d1c82da16279a6"),
"item" : "pen-2",
"colors" : [
"green",
"blue",
"pink",
"purple"
],
"rank" : 0.25
}
/* 2 */
{
"_id" : ObjectId("58c645eaf3d1c82da16279a5"),
"item" : "pen-1",
"colors" : [
"yellow",
"green",
"blue",
"red",
"pink",
"purple"
],
"rank" : 0.5
}