如何在 MongoDB 数组中的集合中统计文档的数量?
若要统计数组中集合中的文档数,请使用 aggregate()。我们创建一个文档集合 -
> db.demo332.insertOne({details:[{Name:"Chris",Age:21}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e521f16f8647eb59e56208e") } > db.demo332.insertOne({details:[{Name:"David",Age:23},{Name:"Bob",Age:22}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e521f21f8647eb59e56208f") }
使用 find() 方法从集合中显示所有文档 -
> db.demo332.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e521f16f8647eb59e56208e"), "details" : [ { "Name" : "Chris", "Age" : 21 } ] } { "_id" : ObjectId("5e521f21f8647eb59e56208f"), "details" : [ { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 22 } ] }
以下是统计数组中集合中文档数的查询 -
> db.demo332.aggregate([ ... { ... $project: { ... numberOfDocuments: { $cond: { if: { $isArray: "$details" }, then: { $size: "$details" }, else: "No Documents"} } ... } ... } ... ] )
这将生成以下输出 -
{ "_id" : ObjectId("5e521f16f8647eb59e56208e"), "numberOfDocuments" : 1 } { "_id" : ObjectId("5e521f21f8647eb59e56208f"), "numberOfDocuments" : 2 }
广告