如何只用MongoDB返回X量的嵌入式文档?

时间:2016-06-09 00:31:05

标签: mongodb

我有一个名为posts的大型集合,如下所示:

[{
   _id: 349348jf49rk,
   user: frje93u45t,
   comments: [{
      _id: fks9272ewt
      user: 49wnf93hr9,
      comment: "Hello world"
   }, {
      _id: j3924je93h
      user: 49wnf93hr9,
      comment: "Heya"
   }, {
      _id: 30283jt9dj
      user: dje394ifjef,
      comment: "Text"
   }, {
      _id: dkw9278467
      user: fgsgrt245,
      comment: "Hola"
   }, {
      _id: 4irt8ej4gt
      user: 49wnf93hr9,
      comment: "Test"
   }]
}]

我的comments子文档有时可能长达100个文档。我的问题是,如何才能返回3个最新文档(基于ID)而不是所有文档,并将所有文档的长度作为计数返回totalNumberOfComments?我有时需要为posts的100个这样做。这是最终结果的样子:

[{
   _id: 349348jf49rk,
   user: frje93u45t,
   totalNumberOfComments: 5,
   comments: [{
      _id: fks9272ewt
      user: 49wnf93hr9,
      comment: "Hello world"
   }, {
      _id: j3924je93h
      user: 49wnf93hr9,
      comment: "Heya"
   }, {
      _id: 30283jt9dj
      user: dje394ifjef,
      comment: "Text"
   }]
}]

我理解这可以在MongoDB通过拼接返回数据后完成,虽然我认为最好在查询中执行此操作,以便Mongo不必为每个{{0}返回所有comments始终{1}}。

1 个答案:

答案 0 :(得分:1)

这可以解决您的问题吗?尝试插入_id值并查看缺少的内容并将其发布到此处。

从此查询开始

db.collection.aggregate([{$match: {_id: 349348jf49rk}},
                        {$project:{
                                    _id:1,
                                     user:1,
                                     totalNumberOfComments: { $size: "$comments" },
                                     comments: {$slice:3}
                                }
                        }
                    ])