【问题标题】:Query operation in Mongodb to find first 10 row from find left outer between two query from the same collectionMongodb 中的查询操作,在同一集合的两个查询之间从 find left outer 中查找前 10 行
【发布时间】:2021-11-14 18:48:29
【问题描述】:

我需要帮助以快速找到来自同一集合的两个查询之间的左外部前 10 个文档。

假设我有以下记录的一个集合:

{ 
    "_id" : NumberLong(1), 
    "clientId" : "1", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(2),
    "clientId" : "2", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(3), 
    "clientId" : "3", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(4), 
    "clientId" : "4", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(5), 
    "clientId" : "5", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(6), 
    "clientId" : "6", 
    "requestId" : "100"
}
{ 
    "_id" : NumberLong(7), 
    "clientId" : "7", 
    "requestId" : "100"
}

{ 
    "_id" : NumberLong(8), 
    "clientId" : "6", 
    "requestId" : "200"
}
{ 
    "_id" : NumberLong(9), 
    "clientId" : "7", 
    "requestId" : "200"
}
{ 
    "_id" : NumberLong(10), 
    "clientId" : "8", 
    "requestId" : "200"
}
....

这里有近 3M 条 requestId:100 的记录和 2M 条 requestId:200 的记录。 我需要找到前 10 条记录,其中客户端 ID 具有“mainRequestId”但不在“excludedRequestId”中。

我的查询是:

let mainRequestId = "100";
let excludedRequestId = "200";

db.collection.aggregate([
  { $match: { requestId: mainRequestId } },
  {
    $lookup: {
      from: "collection",
      localField: "clientId",
      foreignField: "clientId",
      as: "results"
    }
  },
  { $match: { "results.requestId": {$ne: excludedRequestId} } },
  { $limit: 10},
])

我也有索引requesId 和clientId,以及这两个字段的复合索引。但是这个查询需要 2 多分钟。

有没有更好的方法来加快这个操作。

谢谢。

【问题讨论】:

  • 第二个匹配项引用了results 字段,但数据似乎没有?
  • 我已经编辑了问题。
  • requestId 和 clientId 上是否已有索引?

标签: mongodb mongodb-query


【解决方案1】:

将您的$match 放入$lookup pipeline

db.orders.aggregate([
  {
    $match: {
      requestId: "100"
    }
  },
  {
    $lookup: {
      from: "collection",
      pipeline: [
        {
          $match: {
            "requestId": {
              $ne: "200"
            }
          }
        }
      ],
      localField: "clientId",
      foreignField: "clientId",
      as: "results"
    }
  },
  {
    $limit: 10
  }
])

mongoplayground

【讨论】:

  • 我收到错误“$lookup with 'pipeline' may not specified 'localField' or 'foreignField'”。
  • 查看pipeline
  • 我已经检查过了,但是没有一个能解决我的问题。
猜你喜欢
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多