[英]Count elements in an array from a document
我正在嘗試建立一個博客,其中每個帖子包含多個段落。 我只想計算一個特定帖子中的段落數。 在“博客”集合中,我的文檔(=帖子)如下:
{ id : String
title : String
paragraphs : [ { position: Int, body: String } ] }
我想要一個返回整數的函數。 也許接近:
var NumberParagraphs = Blog.find( {id: id} ).paragraphs.length
(顯然這是行不通的!)...您能建議我進行哪種調查嗎? 在網上搜索時,我對.count()
, $size
或.aggregate
用例感到困惑
.find()
方法不返回單個文檔。 因此,您要么要將這些文檔作為數組循環:
Blog.find({ id: id }).fetch().forEach(function(doc) {
var NumParagraphs = doc.paragraphs.length;
// Then do something useful
})
或者只是.findOne()
用於單個文檔:
var doc = Blog.findOne({ id: id });
var NumParagraphs = doc.paragraphs.length;
同樣的原則適用於MongoDB的原始方法,而不僅僅是流星。
還有一個使用聚合方法和$ size的示例,以防萬一您想知道:
var numParagraphs = Blog.aggregate([
{
$match : {
"_id" : id
}
},
{
$project : {
"pCount" : {$size : '$paragraphs'}
}
}
]).pCount;
你應該做
Blog.findOne({_id:id}).paragraphs.length
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.