我有一个这样的Collection

{
 id: 1,
 category: "food",
 score: 20
}
{
 id: 2,
 category: "drink",
 score: 19
}
{
 id: 3,
 category: "food",
 score: 50
}
{
 id: 4,
 category: "food",
 score: 30
}

顺便说一句,id不是唯一的.

所以有可能

{id: 1, category: "food"}
{id: 1, category: "drink"}

但不是

{id: 1, category: "food"}
{id: 1, category: "food"}
here's what I want to do

find all category == "food"
-> it will give id: 1, 3, 4
// I can add some other filter here before sort happen
// like id less than 100

sort them by score
-> it will give id: 3, 4, 1 // highest score must be the first entry

then what is the rank of id: [4, 1]
-> it should give me {id: 4, rank: 2}, {id: 1, rank: 3}

我怎样才能做到这一点?

推荐答案

  db.collection.aggregate([
  {
    "$match": { //Filter conditions
      "category": "food"
    }
  },
  {
    "$sort": {//Sorting
      "score": -1
    }
  },
  {
    "$group": { //Group by null to get array index
      "_id": "null",
      "data": {
        "$push": "$$ROOT",
        
      }
    }
  },
  {
    "$unwind": { //Unwind and get index
      path: "$data",
      "includeArrayIndex": "index"
    }
  },
  {
    "$match": {
      "data.id": { //Filter require ids
        $in: [
          3,
          4
        ]
      }
    }
  }
])

Sample

Mongodb相关问答推荐

如何在Mongo中制作全覆盖索引

无法配置数据源:未指定url属性,无法为 MongoDb 配置嵌入数据源

如何向所有文档添加一个字段,其中前 100 个文档的值为 1,接下来的 100 个文档的值为 2,依此类推?

MongoDb $filter,然后获取非重复计数

Mongodb聚合查找异常值

有没有办法从另一条记录中插入一条记录

MongoDB乘以对象值?

Mongoose 返回包含属性内任何位置的值的所有文档

在推入 mongodb 时自动填充 golang struct 中的 created_at 和 updated_at

使用 mongodb 时是否需要规范化数据库?

如何在 Mongo 聚合管道中获取限制之前的计数

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

什么是 Mongoose (Nodejs) 复数规则?

ExpressJS & Mongoose REST API struct :最佳实践?

如何在mongodb中删除数组的第n个元素

MongoDB 中的所有列

如何在 MongoDB Map-reduce 映射函数中使用变量

mongodb:upserting:仅在插入文档时设置值

MongoDB Compass timeouts超时

我需要手动关闭mongoose连接吗?