mongoose,内嵌文档获取和内嵌文档的数量获取

{
    "_id" : ObjectId("59e05fa63e0f5015dcaeadbe"),
    "name" : "santu",
    "mes" : "测试留言1",
    "time" : ISODate("2017-10-13T06:39:34.273Z"),
    "replay" : [ 
        {
            "time" : ISODate("2017-10-13T06:39:55.365Z"),
            "_id" : ObjectId("59e05fbb3e0f5015dcaeadbf"),
            "replayer" : "santu",
            "replaymes" : "测试留言回复1"
        }
    ],
    "__v" : 0
}

数据结构是这样的,查了一下有这样的获取总数的

db.Scores.aggregate([
 {$project: {'cnt': {$size: '$Scores'}}}
])

而这样写

db.mesModel.aggregate([
 {$project: {num: {$size: '$replay'}}}
])

结果是

[ { _id: 59e05fa63e0f5015dcaeadbe, replay: 1 },
  { _id: 59e063d85f465906606add9a, replay: 1 },
  { _id: 59e063da5f465906606add9b, replay: 1 },
  { _id: 59e063dd5f465906606add9c, replay: 1 } ]

打印了所有的,但是我要用的只是单个数据下的内嵌数据的总数

最终想要的数据是replay下的replaymes,我想的方法是

const mes = req.body.mes 
db.mesModel.findOne({mes:mes},(err,doc)={
    console.log(doc.replay[key].replaymes)
})
阅读 3k
1 个回答

https://docs.mongodb.com/manu...
https://docs.mongodb.com/manu...

给你找来了文档..

  • $project
    Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.
  • $size
    Counts and returns the total the number of items in an array.

aggregate还有很多操作符,你可以一个个慢慢过一遍..

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进