Home > Back-end >  im trying to count returned documents in mongodb with facet and got issue
im trying to count returned documents in mongodb with facet and got issue

Time:02-09

im trying to count the results with $facet and when im adding count its counting but not showing the $project results, if I remove the count then i see the results, im new to mongoDb and still learning , any help will be apprecieted , thanks the code im using right now

db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        },
         {
            $count: "documents"
          }
        
      ]
    }
  }
])

playground

CodePudding user response:

To count the documents you can use $size after the $facet stage.

The main problem in your query is you want to access the documents field into the $facet but the documents are available after $facet is completed.

db.collection.aggregate([
  {
    $facet: {
      documents: [
        {
          "$match": {
            "dstChannel": "",
            "destination": "960",
            "date": {
              "$gte": "2022-01-20 21:43:13",
              "$lte": "2022-01-25 23:43:14"
            }
          }
        },
        {
          "$project": {
            "destination": 1,
            "source": 1,
            "date": 1,
            "duration": 1
          }
        }
        ]
      }
    },
    {
      "$addFields": {
        "nDocuments": {
          "$size": "$documents"
        }
      }
    }
  ])

Example here

  •  Tags:  
  • Related