<p>使用<code>len</code>方法返回数组中的元素数会更容易,但如果您仍然希望聚合查询同时返回计数和实际文档,请尝试使用<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/facet/index.html" rel="nofollow noreferrer">$facet</a>或<code>$group</code>:</p>
<p><strong>查询1:</strong></p>
<pre><code> {
$facet: {
docs: [ { $match: {} } ], // passes all docs into an array field
count: [ { $count: "count" } ] // counts no.of docs
}
},
/** re-create count field from array of one object to just a number */
{
$addFields: { count: { $arrayElemAt: [ "$count.count", 0 ] } }
}
</code></pre>
<p><strong>测试:</strong><a href="https://mongoplayground.net/p/81zaMo0n03S" rel="nofollow noreferrer">mongoplayground</a></p>
<p><strong>查询2:</strong></p>
<pre><code> /** Group all docs without any condition & push all docs into an array field & count no.of docs flowing through iteration using `$sum` */
{
$group: { _id: "", docs: { $push: "$$ROOT" }, count: { $sum: 1 } }
}
</code></pre>
<p><strong>测试:</strong><a href="https://mongoplayground.net/p/TqlUnMxfv2s" rel="nofollow noreferrer">mongoplayground</a></p>
<p><strong>注意:</strong></p>
<p>在当前聚合管道的末尾添加其中一个查询,请记住,如果在<code>$match</code>或<code>$unwind</code>阶段之后没有文档,那么第一个查询将不会有<code>count</code>字段,而是有<code>docs : []</code>,但第二个查询将只返回<code>[]</code>,并对其进行相应的编码</p>