Mongodb 具有优先查询条件的查询Mongoose

Mongodb 具有优先查询条件的查询Mongoose,mongodb,mongoose,Mongodb,Mongoose,我需要找到第一个查询参数匹配的所有文档,如果找不到更多与该查询匹配的文档,则应应用另一个查询参数 例如: db.users.find({ $or: [ { type: typeToSearch }, // First find all users that has type=typeToSearch { active: true } // then if it can't find more users with type=typeToSearch then look for a

我需要找到第一个查询参数匹配的所有文档,如果找不到更多与该查询匹配的文档,则应应用另一个查询参数

例如:

db.users.find({
 $or: [
   { type: typeToSearch },  // First find all users that has type=typeToSearch
   { active: true } // then if it can't find more users with type=typeToSearch then look for active one
]})
.limit(20)
此查询实际执行的操作将首先查找活动用户(取决于集合中的顺序)。
我需要的是-如果我有18个给定类型的用户,那么应该首先返回他们,然后返回2个活动用户。

这是您正在寻找的一个很酷的功能!猫鼬中的任何东西都不能帮你解决这个问题,在npm中我也看不到任何东西能帮到你

对于两个查询,您必须执行以下操作:

const  fancyQuery = async  limit => {
    const first = await db.users.find({ type: typeToSearch }).limit(20)
    let second = [];
    if (first.length < limit)
        second = await  db.users.find({ active: true,
        type:{$ne:typeToSearch}} })
       .limit(20-first.length)
    return [...first, ...second]
}
您将首先按类型过滤结果,然后按非类型过滤结果,最多可激活20项


您也可以使用聚合管道来实现这一点,但我手头没有这样的答案。

谢谢!我想知道是否可以只进行一次查询,但添加一些排序条件。
db.users.find({
    $or: [
        { type: typeToSearch },
        { active: true,
          type: {$ne: typeToSearch}
        }
    ]})
    .limit(40)