Mongo aggregation: Count documents based on array field matching condition

calluna18

I am trying to collects some statistics from a mongo collection using an aggregation pipeline but can not seem to solve my issue.

I have a collection of documents looking like this.

{
    _id: “36723678126”,
    dates: [ 2020-03-10T10:17:48.799Z, 2020-03-10T08:46:50.347Z, 2019-07-11T13:16:17.294Z ]
}

I would like count the number of documents that meet the following conditions

  • At least one date in the last 30 days
  • No dates between 60 and 30 days ago
  • At least one date before 60 days ago

Would really appreciate any help! :)

igorkf

This should solve the problem (https://mongoplayground.net/p/B3LbEo8UaHA):

Test data:

[
  {
    _id: 1,
    dates: [
      ISODate("2020-03-10T10:17:48.799Z"),
      ISODate("2020-03-10T08:46:50.347Z"),
      ISODate("2019-07-11T13:16:17.294Z")
    ]
  },
  {
    _id: 2,
    dates: [
      ISODate("2020-04-10T10:17:48.799Z"),
      ISODate("2020-05-10T08:46:50.347Z"),
      ISODate("2019-10-11T13:16:17.294Z")
    ]
  }
]

Query:

db.collection.aggregate([
  // create the new fields based on the date rules and count occurences of array
  {
    $addFields: {
      "last_30_days": {
        $sum: {
          $map: {
            "input": "$dates",
            "as": "d",
            "in": {
              $cond: {
                "if": {
                  $lte: [
                    "$$d",
                    {
                      $subtract: [
                        "$$NOW",
                        2592000000 // 30 days
                      ]
                    }
                  ]
                },
                "then": 1,
                "else": 0
              }
            }
          }
        }
      },
      "between_30_60": {
        $sum: {
          $map: {
            "input": "$dates",
            "as": "d",
            "in": {
              $cond: {
                "if": {
                  $and: [
                    {
                      $lt: [
                        "$$d",
                        {
                          $subtract: [
                            "$$NOW",
                            2592000000 // days
                          ]
                        }
                      ]
                    },
                    {
                      $gt: [
                        "$$d",
                        {
                          $subtract: [
                            "$$NOW",
                            5184000000 // 60 days
                          ]
                        }
                      ]
                    }
                  ]
                },
                "then": 1,
                "else": 0
              }
            }
          }
        }
      },
      "last_60_days": {
        $sum: {
          $map: {
            "input": "$dates",
            "as": "d",
            "in": {
              $cond: {
                "if": {
                  $lte: [
                    "$$d",
                    {
                      $subtract: [
                        "$$NOW",
                        5184000000
                      ]
                    }
                  ]
                },
                "then": 1,
                "else": 0
              }
            }
          }
        }
      }
    }
  },
  // find which document meet the conditions (1 for true, 0 for false)
  {
    $project: {
      "meet_conditions": {
        $cond: {
          "if": {
            $and: [
              {
                $gt: [
                  "$last_30_days",  // at least one occurence
                  0
                ]
              },
              {
                $eq: [
                  "$between_30_60",  // no occurences
                  0
                ]
              },
              {
                $gt: [
                  "last_60_days",  // at least one occurence
                  0
                ]
              }
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  },
  // count documents, summing the meet_conditions field (because they are 0 or 1)
  {
    $group: {
      _id: null,
      count: {
        $sum: "$meet_conditions"
      }
    }
  }
])

Result:

[
  {
    "_id": null,
    "count": 1
  }
]

So in the example above, there's just one documents that meet your conditions.

Obs.: To calculate the days you have to do (the bold numbers are the day you want):

1 * 1000 * 60 * 60 * 24 * 30 = 2592000000ms = 30 days

1 * 1000 * 60 * 60 * 24 * 60 = 5184000000ms = 60 days

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Mongo aggregation to collect array elements based on field name

分類Dev

Total count and field count with condition in a single MongoDB aggregation pipeline

分類Dev

Total count and field count with condition in a single MongoDB aggregation pipeline

分類Dev

MongoDB - Find documents matching certain condition for unknown field keys

分類Dev

How to sort documents based on length of an Array field

分類Dev

Mongo DB, count documents

分類Dev

Elasticsearch: Matching documents with an array in it

分類Dev

Exclude nested documents based on a condition

分類Dev

Column count based on a condition

分類Dev

Mongo aggregation, project a subfield of the first element in the array

分類Dev

Flutter firestore fetch documents with a condition on a map field

分類Dev

Count from a Count based on a condition in SQL server

分類Dev

Sort Documents based on nested child count in ElasticSearch

分類Dev

SSRS : calculated field based on other field and condition

分類Dev

Running count based on field in R

分類Dev

How to unset a field from all documents with php mongo adapter?

分類Dev

Find Documents Where a Field Compares with Another in an Array

分類Dev

Extract a value from an object in array matching a condition

分類Dev

condition matching in an array with case class in scala

分類Dev

Filter javascript array based on condition

分類Dev

How to Merge Array and Document Field in Mongo DB

分類Dev

R datatable grouping based on condition and getting count based on the conditions

分類Dev

Aggregation on spring mongo

分類Dev

MongoDB How to update the first item that matches a condition in an array of documents?

分類Dev

Elasticsearch: How to query an array field using OR condition?

分類Dev

Push an element into an array if a field satisfies a condition, MongoDB

分類Dev

$sum a field in an array - Query that results documents above a certain value

分類Dev

Finding common values of array field of two documents in ElasticSearch

分類Dev

Filtering out documents with a specific item in an array field using mongoid

Related 関連記事

  1. 1

    Mongo aggregation to collect array elements based on field name

  2. 2

    Total count and field count with condition in a single MongoDB aggregation pipeline

  3. 3

    Total count and field count with condition in a single MongoDB aggregation pipeline

  4. 4

    MongoDB - Find documents matching certain condition for unknown field keys

  5. 5

    How to sort documents based on length of an Array field

  6. 6

    Mongo DB, count documents

  7. 7

    Elasticsearch: Matching documents with an array in it

  8. 8

    Exclude nested documents based on a condition

  9. 9

    Column count based on a condition

  10. 10

    Mongo aggregation, project a subfield of the first element in the array

  11. 11

    Flutter firestore fetch documents with a condition on a map field

  12. 12

    Count from a Count based on a condition in SQL server

  13. 13

    Sort Documents based on nested child count in ElasticSearch

  14. 14

    SSRS : calculated field based on other field and condition

  15. 15

    Running count based on field in R

  16. 16

    How to unset a field from all documents with php mongo adapter?

  17. 17

    Find Documents Where a Field Compares with Another in an Array

  18. 18

    Extract a value from an object in array matching a condition

  19. 19

    condition matching in an array with case class in scala

  20. 20

    Filter javascript array based on condition

  21. 21

    How to Merge Array and Document Field in Mongo DB

  22. 22

    R datatable grouping based on condition and getting count based on the conditions

  23. 23

    Aggregation on spring mongo

  24. 24

    MongoDB How to update the first item that matches a condition in an array of documents?

  25. 25

    Elasticsearch: How to query an array field using OR condition?

  26. 26

    Push an element into an array if a field satisfies a condition, MongoDB

  27. 27

    $sum a field in an array - Query that results documents above a certain value

  28. 28

    Finding common values of array field of two documents in ElasticSearch

  29. 29

    Filtering out documents with a specific item in an array field using mongoid

ホットタグ

アーカイブ