【问题标题】:Spring mongodb unwind on nested fieldSpring mongodb 在嵌套字段上展开
【发布时间】:2019-07-28 14:07:30
【问题描述】:

我正在尝试运行聚合查询,试图展开嵌套在键 customFields 下的数组。

结构是这样的

{
    "note" : {
        "customFields" : {
            "externalAttendees" : [ 
                {
                    "email" : "someemail@domain.com",
                    "epp" : null
                }, 
                {
                    "email" : "anotheremail@domain.com",
                    "epp" : null
                }
            ]
        }
    }
}

customField 是字符串 Object 类型的 Map。当我尝试放松 note.customFields.externalAttendees 时出现错误 找不到对象类型的属性 externalAttendees!遍历路径:Activity.note.customFields。

另一方面,如果我在字段上展开,该字段是一个具体对象的数组,例如 List,其中 User 类有 email 和 epp 作为实例变量,那么我不会遇到任何异常。

有什么方法可以放松动态键,这些键不是 bean 的一部分,但在文档中可用。

我正在使用 springMongoData 数据库聚合。

【问题讨论】:

    标签: mongodb aggregation-framework spring-mongodb spring-mongo


    【解决方案1】:

    看起来文档结构应该具有完全相同的 java 表示。在我的情况下,我分组的 externalAttendees 是 Map 的一部分,而不是 bean 的实例变量。

    我尝试了 MongoTemplate 的 executeCommand(BasicDBObject.parse(stringJson)) ,它解决了目的。

    我的 stringJson 看起来像

    { "aggregate" : "__collection__" , "pipeline" : [ { "$match" : { "note.customFields.externalAttendees" : { "$exists" : true}}} , { "$match" : { "note.customFields.externalAttendees.name" : { "$in" : [ "x" , "y"]}}} , { "$sort" : { "createdDate" : -1}} , { "$unwind" : "$note.customFields.externalAttendees"} , { "$project" : { "id" : 1 , "emailId" : "$note.customFields.externalAttendees.name" , "aType" : "$note.type" , "subject" : "$note.subject"}} , { "$group" : { "_id" : "$emailId" , "type" : { "$first" : "$aType"} , "subject" : { "$first" : "$subject"}}}],"cursor": {"batchSize":10}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-23
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多