Mongo Aggs和总计数

时间:2018-06-28 03:02:39

标签: mongodb aggregation-framework

我在mongodb中遇到了一些麻烦,无法对集合进行查询,以过滤所有文档,分页(带有跳过和限制)并获得类似的总计数

聊天文档如下所示:

{
"_id": "c603db3e75ec76f5a4dff559bc525e29",
"members": [{
  "user": "5b2b0d5135cfd60185034bf6",
  "status": "creator"
}, {
  "user": "5b31dc3f88284a009fa847e5",
  "status": "member"
}],
"messages": [{
  "_id": 2,
  "from": "5b2b0d5135cfd60185034bf6",
  "parse_mode": "none",
  "text": "fffasdfsa",
  "attachment": null,
  "time": 1529995684119,
  "type": "text"
},
{...},
{...}
]}

我想得到这样的结果

{
  total_count: 3,
  chats: [{
    "_id": "c603db3e75ec76f5a4dff559bc525e29",
    "members": [{
      "user": "5b2b0d5135cfd60185034bf6",
      "status": "creator"
    }, {
      "user": "5b31dc3f88284a009fa847e5",
      "status": "member"
    }],
    "creator": {
      "user": "5b2b0d5135cfd60185034bf6",
      "status": "creator"
    },
    "lastMessage": {
      "_id": 4,
      "from": "5b2b0d5135cfd60185034bf6",
      "parse_mode": "none",
      "text": "aasdas",
      "attachment": null,
      "time": 1529995698736,
      "type": "text"
    },
    "messages": [{
      "_id": 2,
      "from": "5b2b0d5135cfd60185034bf6",
      "parse_mode": "none",
      "text": "fffasdfsa",
      "attachment": null,
      "time": 1529995684119,
      "type": "text"
    }, {
      "_id": 3,
      "from": "5b2b0d5135cfd60185034bf6",
      "parse_mode": "none",
      "text": "weqw",
      "attachment": null,
      "time": 1529995690015,
      "type": "text"
    }, {
      "_id": 4,
      "from": "5b2b0d5135cfd60185034bf6",
      "parse_mode": "none",
      "text": "aasdas",
      "attachment": null,
      "time": 1529995698736,
      "type": "text"
    }]
  },
  {...},
  {...}
  ]
}

我的查询是

collection<DbChat>('chats').aggregate([
            {
                $match: {
                    messages: { $exists: true }
                }
            },
            { $unwind: '$messages' },
            { $unwind: '$members' },
            { $group: {_id: '$_id', members:  { $push: '$members' },  member:  { $last: '$members' }, creator:  { $first: '$members' }, messages: {$push: '$messages' } , lastMessage: {$last: '$messages'}}},
            { $sort: this.sort},
        ]}.skip(skip).limit(size)

在此查询中,我没有得到total_count,我尝试了很多事情,但没有找到在同一查询中获取结果和计数的方法。

谢谢

0 个答案:

没有答案