复杂的 MongoDB 查询涉及数组操作

huangapple go评论62阅读模式
英文:

Complex mongodb query with arrays operations

问题

我有一批类似的文档集合:

{
    _id: ObjectId("63f4c47a6edd646542c4a2c9"),
    title: 'ABCDEF',
    counter: 230,
    values: [
      {
        a: 4,
        b: 4,
        date: ISODate("2023-02-21T00:00:00.000Z")
      },
      {
        a: 2,
        b: 4,
        date: ISODate("2023-02-25T00:00:00.000Z")
      }
    ]
}

我想要找到所有counter小于201且具有最高datevalue'b'大于'a'的文档,其比率至少为2。如何实现这一目标?

BR

英文:

I have got a collection of documents like:

{
    _id: ObjectId("63f4c47a6edd646542c4a2c9"),
    title: 'ABCDEF',
    counter: 230,
    values: [
      {
        a: 4,
        b: 4,
        date: ISODate("2023-02-21T00:00:00.000Z")
      },
      {
        a: 2,
        b: 4,
        date: ISODate("2023-02-25T00:00:00.000Z")
      }
    ]
}

I would like to find all documents which have counter less than 201 and which value with the highest date has 'b' greater than 'a' by some minimum ratio: let's say 2.

How to accomplish that?

BR

答案1

得分: 2

如果我理解正确,您可以尝试以下查询:

  • 首先,获取仅具有counter小于201的文档。
  • 然后创建一个辅助字段,其中包含数组中日期元素的最高值。通过对日期进行排序并获取第一个元素来实现这一目标。
  • 然后再次使用$match筛选元素,其中ab之间的比率大于2(即b > a * 2)。
  • 最后一步是使用$project,以便不输出辅助值,仅显示文档本身。

示例在此处

英文:

If I've understood correctly you can try this query:

  • First get only documents with counter less than 201.
  • Then create an aux field with the highest date element from the array. Sorting array by date and getting the first will give desired one.
  • Then $match again to filter elements where the ratio between a and b is greater than 2 (i.e. b > a * 2.).
  • And last step is $project to not output the aux value and only show the document itself.
db.collection.aggregate([
  {
    "$match": {
      "counter": { "$lt": 201 }
    }
  },
  {
    "$set": {
      "auxvalue": {
        "$arrayElemAt": [
          {
            "$sortArray": {
              "input": "$values",
              "sortBy": { "date": -1 }
            }
          },
          0
        ]
      }
    }
  },
  {
    "$match": {
      "$expr": {
        "$gte": [
          "$auxvalue.b",
          {
            "$multiply": [ "$auxvalue.a", 2 ]
          }
        ]
      }
    }
  },
  {
    "$project": { "auxvalue": 0 }
  }
])

Example here

huangapple
  • 本文由 发表于 2023年3月7日 17:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定