【发布时间】:2018-06-27 19:52:20
【问题描述】:
我有两个名为广告和包含的集合。 对于该广告,我需要在当前月份中包含的包含状态为“ACTIVE”和 lastModifiedDate 的计数。
我还有一个关于 adState 是“ACTIVE”的广告条件。
advertisement document
{
"_id" : ObjectId("1231321321321"),
"adNumber":1
"adState" : "ACTIVE"
"company" : "companyABC",
"address" : "123 new road",
"agentName": "Agent_2"
"lastpublish" : ISODate("2018-01-18T20:20:02.262Z"),
"createdDate" : ISODate("2018-01-10T16:03:06.694Z"),
"lastModifiedDate" : ISODate("2018-01-18T20:20:02.262Z"),
"createdBy" : "yasa",
"lastModifiedBy" : "System",
}
contains documents
{
"_id" : ObjectId("465465456456"),
"adNumber":1
"containId": 10
"containState" : "ACTIVE",
"title" : "Increase sales by 10%",
"detials" : "buy this solution to incresce ur sale by 10%",
"agentName": "Agent_2"
"createdDate" : ISODate("2018-01-11T15:03:06.694Z"),
"lastModifiedDate" : ISODate("2018-01-11T15:03:06.694Z"),
"createdBy" : "yasa",
"lastModifiedBy" : "System",
}
{
"_id" : ObjectId("56565656555"),
"adNumber":1
"containId": 11
"containState" : "IN-ACTIVE",
"title" : "Land for sale",
"detials" : "Land near water park for sale",
"agentName": "Agent_2"
"createdDate" : ISODate("2018-01-11T15:30:01.694Z"),
"lastModifiedDate" : ISODate("2018-01-12T15:03:06.694Z"),
"createdBy" : "yasa",
"lastModifiedBy" : "System",
}
{
"_id" : ObjectId("56887423587"),
"adNumber":1
"containId": 12
"containState" : "ACTIVE",
"title" : "car for sale",
"detials" : "BMW for sale",
"agentName": "Agent_2"
"createdDate" : ISODate("2018-01-11T15:45:01.690Z"),
"lastModifiedDate" : ISODate("2018-01-11T15:45:01.690Z"),
"createdBy" : "yasa",
"lastModifiedBy" : "System",
}
给出代码示例以在 java 中将其合并到 spring-data、mongodb 上。
还建议获得结果聚合或映射减少的最佳方法
聚合查询
db.advertisement.aggregate([
{$match:{"adState": "ACTIVE", "agentName": "Agent_2"}},
{$lookup:
{
from: "contains",
localField: "adNumber",
foreignField: "adNumber",
as: "result_ad"
}},
{$project:{result_ad:1}},
{$match:{"result_ad": {'$ne': []}}},
{$unwind:"$result_ad"},
{$match:{"result_ad.containState" : "ACTIVE"}},
{$group: { _id: null, count: { $sum: 1 } }}])
【问题讨论】:
-
你试过什么?请向我们展示您拥有的代码,有人会从那里帮助您。这两个集合是否相互关联?您预期的输出 json 是什么?添加您用来获得准确答案的所有 pojo。
-
@Veeram 我为此编写了一个 mongodb 查询,我不知道使用 spring-data 也我需要过滤正在进行的月份。我在问题上添加了 mongodb 聚合查询
标签: java mongodb spring-data aggregation-framework spring-data-mongodb