是否计算Array内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 }