Node.js 子文档中的Mongoose计数项目
我有以下模式:Node.js 子文档中的Mongoose计数项目,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有以下模式: { _id: 1, post: 'content', comments: [ { id: 1, items: ['<other_doc_id',...] // assume 3 items }, { id: 2, items: ['<other_doc_id',...] // assume 2 item
{
_id: 1,
post: 'content',
comments: [
{
id: 1,
items: ['<other_doc_id',...] // assume 3 items
},
{
id: 2,
items: ['<other_doc_id',...] // assume 2 items
}
]
}
查询
posts.aggregate([{
"$project": {
"count": {
"$sum": {
"$map": {
"input": "comments",
"as": "result",
"in": {
"$size": "$$result.items"
}
}
}
}
}
}]);
您可以使用
$map
计算文档注释数组中每个项目的$size
,然后使用$sum
计算所有大小
db.collection_name.aggregate([
{
"$project": {
"count": {
"$sum": {
"$map": {
"input": "$comments",
"as": "result",
"in": {
"$size": "$$result.items"
}
}
}
}
}
}
])
您可以使用
$map
计算文档注释数组中每个项目的$size
,然后使用$sum
计算所有大小
db.collection_name.aggregate([
{
"$project": {
"count": {
"$sum": {
"$map": {
"input": "$comments",
"as": "result",
"in": {
"$size": "$$result.items"
}
}
}
}
}
}
])
谢谢,这是有道理的,但它给了我以下错误:
MongoError:$map的输入必须是数组而不是字符串
这个答案对我很有用,并且不会导致任何错误。@Veeram我使用的查询与你的相同,我用我拥有的示例数据更新了我的问题。工作正常,并输出{count:2}
为我提供您提供的数据。请将查询添加到问题中。可能有一些输入错误。@Veeram query AddedHanks,这是有道理的,但它给了我以下错误:MongoError:$map的输入必须是数组而不是字符串
这个答案对我很有用,不会导致任何错误。@Veeram我使用的查询与你的相同,我已经用我拥有的样本数据更新了我的问题。效果很好,并用您提供的数据为我输出{count:2}
。请将查询添加到问题中。“可能有一些输入错误。”添加了Veeram查询