在mongodb中获取内部子数组内容作为查询结果

时间:2019-03-08 06:06:13

标签: mongodb mongoose

我有一个期刊集,其中包含期刊的详细信息,数量,期刊和文章。我需要从以下集合中获取问题名称和文章数。条件将是:

_id = ObjectId(“ 5c7faf8384bbfc127f171222”)

jnl_volumes.name = 1


这是我的文档:

{
    "_id":ObjectId("5c7faf8384bbfc127f171222"),
    "jnl_code":"QWER",
    "jnl_title":"Title",
    "jnl_short_title":"short",
    "jnl_accronym":"accronym",
    "jnl_issn":"issn",
    "jnl_eissn":"eissn",
    "jnl_license_type":{
        "name":"Open access",
        "value":"o"
    },
    "jnl_category":{
        "name":"Science",
        "value":"s"
    },
    "jnl_volumes":[
        {
            "name":1,
            "created_date":"2019-03-06",
            "status":"0",
            "issue_flag":"0",
            "jnl_issues":[
                {
                    "issue_name":"2",
                    "created_date":"2019-03-07",
                    "jnl_articles":[
                        "ART 1",
                        "ART 2"
                    ]
                },
                {
                    "issue_name":"3",
                    "created_date":"2019-03-07",
                    "jnl_articles":[
                        "A 1"
                    ]
                },
                {
                    "issue_name":"4",
                    "created_date":"2019-03-07",
                    "jnl_articles":[
                        "AR 1"
                    ]
                }
            ]
        },
        {
            "name":2,
            "created_date":"2019-03-06",
            "status":"0",
            "issue_flag":"0",
            "jnl_issues":[
                {
                    "issue_name":"1",
                    "created_date":"2019-03-07",
                    "jnl_articles":[
                        "Article 1",
                        "Article 2",
                        "Article 3",
                        "Article 4",
                        "Article 5"
                    ]
                }
            ]
        }
    ],
    "jnl_created_by":"1",
    "jnl_status":"a",
    "jnl_proxy_id":"0",
    "jnl_operation":"i",
    "jnl_updated_date":ISODate("2019-03-07T11:05:21.000Z"),
    "jnl_created_date":ISODate("2019-03-07T11:05:21.000Z")
}

我希望结果包含jnl_issues.name和其中的jnl_articles个计数。...

1 个答案:

答案 0 :(得分:0)

以下是使用mongodb聚合的结果,可能还有优化的空间,但是我仍然不知道如何优化它。

db.test.aggregate([
  { $match: { '_id': ObjectId("5c7faf8384bbfc127f171222") } },
  { $project: { 'jnl_volumes': 1 } },
  { $unwind: '$jnl_volumes' },
  { $match: { 'jnl_volumes.name': 1 } },
  { $group: { '_id': null, 'info': { $push: '$jnl_volumes.jnl_issues' } } },
  { $unwind: '$info' },
  { $unwind: '$info' },
  { $project: { 'name': '$info.issue_name', 'count': { $sum: { $size: '$info.jnl_articles' } } } }
])

这是我的结果:

enter image description here