MongoDB/Mongoose使用聚合获取对象的数组属性的长度
我尝试将$size用于聚合,但出现以下错误: MongoError:未知的组运算符“$size” 我使用的是mongodb 3.6版。我只想得到comments属性的长度,它是一个数组 下面是一个示例问题文档:MongoDB/Mongoose使用聚合获取对象的数组属性的长度,mongodb,mongoose,Mongodb,Mongoose,我尝试将$size用于聚合,但出现以下错误: MongoError:未知的组运算符“$size” 我使用的是mongodb 3.6版。我只想得到comments属性的长度,它是一个数组 下面是一个示例问题文档: Problem.aggregate( [ { $unwind: "$comments" }, { $group: { _id: "$_id", size: { $size: "$comments"
Problem.aggregate(
[
{ $unwind: "$comments" },
{
$group: {
_id: "$_id",
size: { $size: "$comments" }
}
}
],
function(err, results) {
console.log(err);
console.log(results);
}
);
我不想得到的数组,我只想得到数组的长度。如果有另一种方法不使用聚合,那也可以:)提前谢谢 试试这样的东西
{
"_id": {
"$oid": "5e02a2184a6e7f4980f47e8f"
},
"author": {
"id": {
"$oid": "5e027a4badd90919304a9eb0"
}
},
"description": "testd",
"gender": 0,
"dailyUpvotes": 2,
"tags": [
{
"_id": {
"$oid": "5e02a2184a6e7f4980f47e90"
},
"name": "test"
}
],
"title": "test",
"upVotes": 2,
"comments": [
{
"_id": {
"$oid": "5e03124933c17d406471d6f9"
},
"id": {
"$oid": "5e03124933c17d406471d6f8"
}
}
],
"upVotesList": [
{
"_id": {
"$oid": "5e045a07745eb94b584d27e1"
},
"userID": {
"$oid": "5e045a00745eb94b584d27e0"
}
},
{
"_id": {
"$oid": "5e02a26b3cbe4e3794555f42"
},
"userID": {
"$oid": "5e027a4badd90919304a9eb0"
}
}
],
"createdAt": {
"$date": "2019-12-24T23:41:12.707Z"
},
"updatedAt": {
"$date": "2019-12-26T06:58:15.080Z"
},
"__v": 2
}
请点击查看,您可以添加样本文档吗?@cuonglongoc完成!这回答了你的问题吗?
Problem.aggregate([
{
$project: {
item: 1,
numberOfResults: { $size: "$comments" }
}
}
] )