【问题标题】:Mongo query to get field from nested documentMongo查询从嵌套文档中获取字段
【发布时间】:2022-04-06 17:55:15
【问题描述】:

我有一个这样的 mongo 集合:

Collection :rResponse
{
    "_id" : ("59c8248 "),
    "correlationId" : ("b92b3 "),
    "rtResponse" : {
        "rTiming" : {
            "servicetime" : "2020-04-17 11:50:42.1053555 (GMT-04:00)"
}

我正在尝试使用查找查询来访问服务时间。

db.rResponsee.rtResponse.rTiming.find( { servicetime: '2020-05-01 08:25:58.4083775 (GMT-04:00)' } );

但它返回 0 行。任何帮助/建议将不胜感激。

【问题讨论】:

    标签: mongodb-query nested-documents


    【解决方案1】:

    您的语法已关闭,该字段的整个路径需要出现在对 find(...) 的调用中:

    db.rResponsee.find({
        'rtResponse.rTiming.servicetime': '2020-05-01 08:25:58.4083775 (GMT-04:00)'
    });
    

    【讨论】:

    • 感谢您的快速回复。它仍然抛出错误:错误:第 1 行:意外令牌。
    【解决方案2】:
    db.rResponse.find({ 'rtResponse.rTiming.servicetime': '2020-04-17 11:50:42.1053555 (GMT-04:00)' }, { 'rtResponse.rTiming.servicetime': 1 })
    

    输出:

    {
        "_id" : "59c8248",
        "rtResponse" : {
            "rTiming" : {
                "servicetime" : "2020-04-17 11:50:42.1053555 (GMT-04:00)"
            }
        }
    }
    

    在这里,我们使用 .find 方法查询“servicetime”,在您的情况下它是嵌套文档,并使用点表示法查询它,即“rtResponse.rTiming.servicetime”。 我们正在使用投影来指定要包含的字段。考虑 { 'rtResponse.rTiming.servicetime': 1 } 其中 1 表示 true 或包含该字段。

    您可以阅读有关 .find 方法 here 和 mongodb 投影 here 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多