【问题标题】:How to get single field in mongodb query?如何在mongodb查询中获取单个字段?
【发布时间】:2022-01-17 13:31:55
【问题描述】:

我有这样的数据:

{ id : 1, 
    book: "Flash", 
    chapters: [
        { 
      chap_no: "1", 
      sub_chapter: [
                {sub_no: 1, description: "<description>"
                },
                {sub_no: 2, description: "<description>"
                },
            ]
        }
    ]
}

我想根据 book -> chapter_no -> sub_no 显示一个像这样的字段

{
 sub_no: 2, description: "<description>"
}

在 mongodb 查询中。

【问题讨论】:

    标签: java arrays json mongodb


    【解决方案1】:

    你可以这样做

    db.collection.aggregate([
      {
        "$match": {
          $and: [
            {
              "book": "Flash3"
            },
            {
              "chapters.chap_no": "2"
            },
            {
              "chapters.sub_chapter.sub_no": "1"
            }
          ]
        }
      },
      {
        "$unwind": "$chapters"
      },
      {
        "$unwind": "$chapters.sub_chapter"
      },
      {
        "$match": {
          $and: [
            {
              "book": "Flash3"
            },
            {
              "chapters.chap_no": "2"
            },
            {
              "chapters.sub_chapter.sub_no": "1"
            }
          ]
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$chapters.sub_chapter"
        }
      }
    ])
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:
    • $match
    • $unwind
    • $unwind
    • $match
    • $replaceRoot
    db.collection.aggregate([
      {
        "$match": {
          "chapters.sub_chapter.sub_no": 2
        }
      },
      {
        "$unwind": "$chapters"
      },
      {
        "$unwind": "$chapters.sub_chapter"
      },
      {
        "$match": {
          "chapters.sub_chapter.sub_no": 2
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$chapters.sub_chapter"
        }
      }
    ])
    

    mongoplayground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-10
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多