【问题标题】:MongoDb: how to combine result of say 5 match queries on a Collection and also sort result ordered by queries resultMongoDb:如何在集合上组合 5 个匹配查询的结果以及按查询结果排序的结果
【发布时间】:2016-03-31 23:37:08
【问题描述】:

我有一个类似这样的架构:

new Schema({
    first: { type: String, required: true, trim: true },
    last: { type: String, trim: true },
    third: { type: Schema.Types.ObjectId },
    fourth: { type: Schema.Types.ObjectId },
    fifth: { type: Schema.Types.ObjectId }
},options);

mongoose.model('User', schema);

假设我在这个集合中有 1000 个文档。

我想以这样的方式对这些文档进行排序:

首先,我们有与特定用户的所有字段值匹配的文档(即与特定文档的所有五个字段值匹配)

然后匹配该用户的下四个字段,然后匹配下三个字段 字段等等。

说第一个匹配找到了 100 个文档,

然后第二个将找到之前的 100 + 200(即与该用户的下三个字段匹配的新 200 个文档)等等。

经过这个计算,我想先显示第一个匹配排序结果,然后显示第二个匹配排序结果,依此类推。

如何使用猫鼬做到这一点?

【问题讨论】:

  • 按什么字段排序?

标签: node.js mongodb mongoose


【解决方案1】:

您需要使用聚合。

[{ 
    $project: {
        _id: 1,
        matchCount: {
            $sum: {
                { $cond: { if: { $eq: ['$first', first] } }, then: 1, else: 0 },
                { $cond: { if: { $eq: ['$last', last] } }, then: 1, else: 0 },
                { $cond: { if: { $eq: ['$third', third] } }, then: 1, else: 0 },
                { $cond: { if: { $eq: ['$fourth', fourth] } }, then: 1, else: 0 },
                { $cond: { if: { $eq: ['$fifth', fifth] } }, then: 1, else: 0 },
            }
        }
    }
},
{
    $sort: {
        matchCount: -1
    }
},
{
    $limit: 200
}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2019-02-05
    • 1970-01-01
    相关资源
    最近更新 更多