我想使用Spring Data通过Java应用程序从MongoDB获取数据。
我按照MongoDB查询并成功转换为Java代码
db.getCollection('financialMessage').aggregate([{
$match:{ createdDate: {
$gte: ISODate("2017-11-03 00:00:00.000Z"),
$lt: ISODate("2017-11-04 00:00:00") }}}, {
$group: { _id: {
consolidatedBatchId: "$consolidatedBatchId",
version: "$version"},
messages: { $addToSet: "$message" }}}, {
$sort: {
"_id.consolidatedBatchId": 1,
"_id.version": 1}
}])
结果如下:
{
"_id" : {
"consolidatedBatchId" : "5f4e1d16-2070-48ef-8369-00004ec3e8ee",
"version" : 4
},
"messages" : [
"message1",
"message2",
"message3"
]
}
上述查询的Java代码如下所示:
Criteria filterCriteria = Criteria.where(CREATED_DATE)
.gte(startDate)
.lt(endDate);
Sort sort = new Sort(Sort.Direction.DESC, "consolidatedBatchId" ,"version");
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(filterCriteria),
Aggregation.group("consolidatedBatchId", "version")
.addToSet("message").as("messages"),
Aggregation.sort(sort)
);
AggregationResults<FinancialMessageKey> aggregationResults =
mongoTemplate.aggregate(agg, FinancialMessage.class, FinancialMessageKey.class);
return aggregationResults.getMappedResults();
现在我找不到如何将以下MongoDB查询代码转换为Java代码:
db.getCollection('financialMessage').aggregate([{
$match:{ createdDate: {
$gte: ISODate("2017-11-03 00:00:00.000Z"),
$lt: ISODate("2017-11-04 00:00:00")
}}}, {
$group: { _id: {
consolidatedBatchId: "$consolidatedBatchId",
version: "$version"},
messages: { $addToSet: {message: "$message",
createdDate: "$createdDate",
sender: "$sender",
receiver: "$receiver" }}}}, {
$sort: {
"_id.consolidatedBatchId": 1,
"_id.version": 1}
}])
使用以下输出:
{
"_id" : {
"consolidatedBatchId" : "5f4e1d16-2070-48ef-8369-00004ec3e8ee",
"version" : 4
},
"messages" : [
{
"message" : "message1",
"createdDate" : ISODate("2017-11-03T07:13:08.074Z"),
"sender" : "sender",
"receiver" : "receiver"
},
{
"message" : "message2",
"createdDate" : ISODate("2017-11-03T07:13:08.111Z"),
"sender" : "sender",
"receiver" : "receiver"
},
{
"message" : "message3",
"createdDate" : ISODate("2017-11-03T07:13:07.986Z"),
"sender" : "sender",
"receiver" : "receiver"
}
]
}
这个addToSet()如何用Java编写以获得List&lt;&#39;复杂对象&#39;&gt;而不是简单的List?
答案 0 :(得分:0)
经过几分钟的谷歌研究,我终于找到了如何做到这一点。
public List<FinancialMessageKey> findFinancialMessageKeys(FinancialMessageQueryDTO financialMessageQueryDTO) {
Criteria filterCriteria = Criteria.where(CREATED_DATE)
.gte(startDate)
.lt(endDate);
Sort sort = new Sort(Sort.Direction.DESC, "consolidatedBatchId", "version");
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(filterCriteria),
Aggregation.group(CONSOLIDATED_BATCH_ID, VERSION)
.addToSet(new BasicDBObject() {
{
put(CREATED_DATE, "$" + CREATED_DATE);
put(SENDER, "$" + SENDER);
put(RECEIVER, "$" + RECEIVER);
put(MESSAGE, "$" + MESSAGE);
}
}
).as("messages"),
Aggregation.sort(sort));
AggregationResults<FinancialMessageKey> aggregationResults =
mongoTemplate.aggregate(agg, FinancialMessage.class, FinancialMessageKey.class);
return aggregationResults.getMappedResults();
}