[英]mongodb get document with max length of a specific array field nodejs
[英]MongoDB query to get the sum of all document's array field length
下面是一個集合的示例文檔,比如“CollectionA”
{
"_id" : ObjectId("5ec3f19225701c4f7ab11a5f"),
"workshop" : ObjectId("5ebd37a3d33055331eb4730f"),
"participant" : ObjectId("5ebd382dd33055331eb47310"),
"status" : "analyzed",
"createdBy" : ObjectId("5eb7aa24d33055331eb4728c"),
"updatedBy" : ObjectId("5eb7aa24d33055331eb4728c"),
"results" : [
{
"analyze_by" : {
"user_name" : "m",
"user_id" : "5eb7aa24d33055331eb4728c"
},
"category_list" : [
"Communication",
"Controlling",
"Leading",
"Organizing",
"Planning",
"Staffing"
],
"analyzed_date" : ISODate("2020-05-19T14:48:49.993Z"),
}
],
"summary" : [],
"isDeleted" : false,
"isActive" : true,
"updatedDate" : ISODate("2020-05-19T14:48:50.827Z"),
"createdDate" : ISODate("2020-05-19T14:47:46.374Z"),
"__v" : 0
}
我需要查詢所有文檔以獲取“結果”數組長度並返回所有文檔“結果”長度的總和。
例如,
文檔 1 的“結果”長度 - 5
文檔 2 的“結果”長度 - 6
那么 output 應該是 11。
我們可以編寫一個查詢,而不是獲取所有,迭代並添加結果長度嗎?
如果我清楚地了解您想投影結果屬性的長度。 因此,您應該檢查 $size 運算符是否適合您。 https://docs.mongodb.com/manual/reference/operator/aggregation/size/
您可以使用$group
和$sum
來計算包含結果數組大小的字段的總大小。 要創建字段,您可以使用$size
$addFields
中的 $size 來計算每個文檔中結果的大小並將其放入字段。 如下:
db.getCollection('your_collection').aggregate([
{
$addFields: {
result_length: { $size: "$results"}
}
},
{
$group: {
_id: '',
total_result_length: { $sum: '$result_length' }
}
}
])
您使用帶有$sum
和$size
聚合運算符的聚合分組查詢來獲取集合中所有文檔的數組元素大小的總和。
db.collection.aggregate( [
{
$group: {
_id: null,
total_count: { $sum: { $size: "$results" } }
}
}
] )
Model.aggregate()
進行聚合:
SomeModel.aggregate([ { $group: { _id: null, total_count: { $sum: { $size: "$results" } } } } ]). then(function (result) { console.log(result); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.