如何在SpringMongo中使用$ objectToArray?

时间:2019-05-07 20:10:53

标签: spring-mongodb

在以下查询中,我试图在SgringMongo中使用$ objectToArray mongo聚合函数。有谁可以帮助我吗?

我找不到任何将其转换为SpringMongo查询的方法

db.getCollection('application').aggregate([
    {$project: {
        people: {$objectToArray: '$applicants.people'},
        doc: '$$ROOT'
        }
    },
    {$match:{'people.v.personName.firstName':  /.*ad.*/i, 'people.v.disabled': true}},
    {$replaceRoot: {newRoot: '$doc'}}
])

2 个答案:

答案 0 :(得分:0)

简而言之,这是这样的方式:

var aggregation = newAggregation(
   Application.class,
   project().and(ObjectOperators.valueOf("applicants.people")
            .toArray())
            .as("people"));

mongoTemplate.aggregate(aggregation, Application.class, OutputModel.class);

它将为您生成以下阶段的汇总:

[
    {
      "$project": {
        "people": {
          "$objectToArray": "$applicants.people"
        }
      }
    }
]

详细信息

假设您具有以下模型:

@Document(collection = "application")
@TypeAlias(alue = "application")
@AllArgsConstructor // lombok annotation
public class Application {
  String id;
  Applicants applicants;

  @Value  // lombok annotation
  public static class Applicants {
    Map<String, Person> people;
  }

  @Value
  public static class Person {
    PersonName personName;
    boolean disabled;
  }

  @Value
  public static class PersonName {
    String firstName;
    String lastName;
  }
}

上面的MongoDB文档的示例可以是:

{
    "_id" : "id-1",
    "applicants" : {
        "people" : {
            "person1" : {
                "personName" : {
                    "firstName" : "Ziemowit",
                    "lastName" : "Stolarczyk"
                },
                "disabled" : true
            },
            "person2" : {
                "personName" : {
                    "firstName" : "Denio",
                    "lastName" : "Pimentel"
                },
                "disabled" : false
            }
        }
    },
    "_class" : "application"
}

从顶部通过代码生成的投影将为您提供输出:

{
    "_id" : "id-1",
    "people" : [
        {
            "k" : "person2",
            "v" : {
                "personName" : {
                    "firstName" : "Denio",
                    "lastName" : "Pimentel"
                },
                "disabled" : false
            }
        },
        {
            "k" : "person1",
            "v" : {
                "personName" : {
                    "firstName" : "Ziemowit",
                    "lastName" : "Stolarczyk"
                },
                "disabled" : true
            }
        }
    ]
}

答案 1 :(得分:-1)

尝试:

Document doc = new Document ("people", ObjectOperators.valueOf("$applicants.people").toArray().toDocument(Aggregation.DEFAULT_CONTEXT));

它将给出为:

{"people": {$objectToArray: '$applicants.people'}}