Home > Mobile >  Get count of returned documents in $lookup pipeline before $limit - MongoDB
Get count of returned documents in $lookup pipeline before $limit - MongoDB

Time:06-16

I have this $lookup pipeline stage:

{ 
  $lookup: {
        'from': 'comments',
        'localField': '_id',
        'foreignField': 'contentId',
        'as': 'comments',
        'pipeline': [{
          '$match': {
            'contentType': 'blog',
            'replyId': null
          }
        }, {
         '$skip': 2
        }, {
         '$limit': 1
        }]
      }
}

Is it possible to get the count of documents returned after the $match stage of the $lookup pipeline and projected into my main pipeline (ie the pipeline that $lookup is a part of)?

Thanks

CodePudding user response:

One option is to use $facet:

{ 
  $lookup: {
        'from': 'comments',
        'localField': '_id',
        'foreignField': 'contentId',
        'as': 'comments',
        'pipeline': [
          {$match: {'contentType': 'blog', 'replyId': null}},
          {$facet: {
            data:[{'$skip': 2}, {'$limit': 1}],
            total:[{$group:{_id: null, count: {$sum: 1}}}]
          }}]}
}

The format is clear, but all the documents you return from the $lookup pipeline are grouped to one document under data.

The other option is to use $setWindowFields:

{ 
  $lookup: {
        'from': 'comments',
        'localField': '_id',
        'foreignField': 'contentId',
        'as': 'comments',
        'pipeline': [
          {$match: {'contentType': 'blog', 'replyId': null}},
          {$setWindowFields: {output: {totalCount: {$count: {}}}}}
         ]}
}

This will add the totalCount to all returned documents, so you need to format it, but the advantage is that your $lookup pipeline results are different documents.

  • Related