【问题标题】:Mongo DB: Sorting by the number of matchesMongodb:按匹配数排序
【发布时间】:2014-02-15 16:14:44
【问题描述】:

我有一个对象数组,我想在 MongoDB 集合中查询具有与我的对象数组中的任何对象匹配的元素的文档。

例如:

var objects = ["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde", "52d91cd69188818e3964917b"];

db.scook.recipes.find({products: { $in: objects }}

但是,我想知道是否可以按 MongoDB 中的匹配数对结果进行排序。

例如,顶部将是恰好匹配三个元素的“食谱”:["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde", "52d91cd69188818e3964917b"]

第二个选择有两个配方:即["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde"],第三个只有一个:即["52d58496e0dca1c710d9bfdd"]

如果你能得到它拥有的物品数量,那就太好了。

【问题讨论】:

  • 我认为您在这里有三个选择:MongoDB 聚合框架、MongoDB Map-Reduce 和操作服务器中的数据。如果我有时间,我会尝试用一个例子来回答。

标签: arrays mongodb sorting mongoose


【解决方案1】:

通过使用聚合框架,我认为你应该可以通过下面的MongoDB查询得到你需要的东西。但是,如果您使用的是 Mongoose,则必须将其转换为 Mongoose 查询。我不确定这是否会完全按原样工作,因此您可能需要稍微尝试一下才能使其正确。此外,这个答案取决于您是否可以在 $project 运算符中使用 $or 运算符,并且它将返回 true。如果这不起作用,我认为您需要使用 map-reduce 来获取您需要的内容或在服务器端进行操作。

db.recipes.aggregate(
    // look for matches
    { $match : { products : { $or : objects }}},
    // break apart documents to by the products subdocuments
    { $unwind : "$products" },
    // search for matches in the sub documents and add productMatch if a match is found
    { $project : {
        desiredField1 : 1,
        desiredField2 : 1,
        products : 1,
        // this may not be a valid comparison, but should hopefully
        // be true or 1 if there is a match
        productMatch : { "$products" : { $or : objects }}
    }},
    // group the unwound documents back together by _id
    { $group : {
        _id : "$_id",
        products : { $push : "$products" },
        // count the matched objects
        numMatches : { $sum : "$productMatch" },
        // increment by 1 for each product
        numProducts : { $sum : 1 }
    }},
    // sort by descending order by numMatches
    { $sort : { numMatches : -1 }}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多