【问题标题】:MongoDB sub Documents fetch as different documents with document count using NestJsMongoDB 子文档使用 NestJs 获取具有文档计数的不同文档
【发布时间】:2021-03-19 16:52:09
【问题描述】:

我有这样的 MongoDb 文档, 所以我需要编写一个查询 => {"enrolments.date" : { $gte:"2020-12-01T00:00:00.000Z"} },但我需要将这些文档作为单独的文档,在本例中,文档计数二,那我该怎么办?

    "_id" : "10000",
    "Class" : "A",
    "enrolments" : [ 
        {"id" : "10000-1","name" : "Test1","month":"2020-11","date":"2020-12-08T10:37:00.000Z"},
        {"id" : "10000-2","name" : "Test2","month":"2020-12","date":"2020-12-07T10:37:00.000Z"},
        {"id" : "10000-3","name" : "Test3","month":"2020-12","date":"2020-11-16T10:37:00.000Z"}
    ]
}

Output =>

    "_id":"10000",
    "Class":"A",
    "enrolments":[ 
        {"id":"10000-1","name":"Test1","month":"2020-11","date":"2020-12-08T10:37:00.000Z"}
    ]
},{
    "_id" : "10000",
    "Class" : "A",
    "enrolments" : [
        {"id" : "10000-2","name" : "Test2","month":"2020-12","date":"2020-12-07T10:37:00.000Z"}
    ]
}

like this

【问题讨论】:

    标签: mongodb mongoose nestjs


    【解决方案1】:

    您正在寻找的是$unwind。所以你应该这样写:

    db.collection.aggregate( [ 
    { 
         $unwind : "$enrolments" 
    },
    {
         $match : { "$enrolments.date" : { $gte:"2020-12-01T00:00:00.000Z"} }
    } 
    ] )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2017-06-29
      • 2014-02-02
      • 2014-09-26
      • 2015-09-02
      相关资源
      最近更新 更多