【问题标题】:MongoDB/Mongoose Get length of array attribute of object using aggregation [duplicate]MongoDB / Mongoose使用聚合获取对象数组属性的长度[重复]
【发布时间】:2019-12-27 11:03:31
【问题描述】:
 Problem.aggregate(
    [
      { $unwind: "$comments" },
      {
        $group: {
          _id: "$_id",
          size: { $size: "$comments" }
        }
      }
    ],
    function(err, results) {
      console.log(err);
      console.log(results);
    }
  );

我尝试将 $size 与聚合一起使用,但出现此错误:

MongoError: 未知组运算符“$size”。

我使用的是 mongodb 3.6 版。我只想获取 cmets 属性的长度,它是一个数组。

这是一个示例问题文档:

{
    "_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
}

我不想得到 的数组,我只想得到数组的长度。如果有另一种不使用聚合的方式,那也很好:) 提前致谢!

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

试试这样的。

Problem.aggregate([
   {
      $project: {
         item: 1,
         numberOfResults: { $size: "$comments" }
      }
   }
] )

看看https://docs.mongodb.com/manual/reference/operator/aggregation/size/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多