我在两件事上需要帮助。
- 使用 spring mongo模板从mongo查询中创建Spring mongoquery。
过滤结果,并仅从具有json树结构的文档中获取较低级别的对象。
我只想通过以下方式获取匹配的 merchant_shops 的列表 community_id,package_type_id和category_id的列表。
我正在使用mongodb版本4。 预先谢谢你。
文档:
{
"_id" : ObjectId("5bdafff206ba681e30895e50"),
"community_id" : "09a5c059-33b3-4e47-9905-709f5c244580",
"package_types" : [
{
"package_type_id" : 1,
"categories" : [
{
"category_id" : "5bd0433d8ac2ce275082ff1f",
"subcategories" : [
{
"subcategory_id" : "5bd0436d8ac2ce275082ff20",
"merchant_shops" : [
{
"shop_id" : "5bd19a704ab492427d7326a0",
"distance" : 14.2841995007249
},
{
"shop_id" : "5bd84aed4ab4926fb2060e76",
"distance" : 14.283313487973
},
{
"shop_id" : "5bdc14ad4ab492123f29c6a7",
"distance" : 14.2829648551977
},
{
"shop_id" : "5be9555e4ab4923a01c7b7f8",
"distance" : 11.8215058435006
},
{
"shop_id" : "5be95a974ab4923a01c7b7fc",
"distance" : 11.8081739265758
}
]
}
]
}
]
},
{
"package_type_id" : 3,
"categories" : [
{
"category_id" : "5bd0433d8ac2ce275082ff1f",
"subcategories" : [
{
"subcategory_id" : "5bd0436d8ac2ce275082ff20",
"merchant_shops" : [
{
"shop_id" : "5bd84aed4ab4926fb2060e76",
"distance" : 14.283313487973
}
]
}
]
}
]
}
]
}
在mongodb中正常工作的查询:
db.getCollection('community_shop').aggregate([
{ $match: {"community_id": "09a5c059-33b3-4e47-9905-709f5c244580"} },
{ $project:
{
package_types:
{$filter: {
input: '$package_types',
as: 'item',
cond: {
$or: [
{
$in: ['$$item.package_type_id', [1,3]]
},{
$eq: ['$$item.categories.category_id', "5bd0433d8ac2ce275082ff1f"]
}
]
}
}}
}
}
])
Java类是:
@Document(collection = "community_shop")
public class CommunityShopDOB {
@Id
private String id;
@Field("community_id")
private String communityId;
@Field("package_types")
private List<PackageType> packageTypes;
public static class PackageType {
@Field("package_type_id")
private Integer packageTypeId;
@Field("categories")
private List<Category> categories;
public static class Category {
@Field("category_id")
private String categoryId;
@Field("subcategories")
private List<Subcategory> subcategories;
public static class Subcategory {
@Field("subcategory_id")
private String subcategoryId;
@Field("merchant_shops")
private List<MerchantShop> merchantShops;
public static class MerchantShop {
@Field("shop_id")
private String shopId;
@Field("distance")
private Double distance;
@Field("filter_value_ids")
private List<String> filterValueIds;
}
}
}
}
到目前为止,我的解决方案是错误的:
Criteria cr = Criteria.where("communityId").is(society_id);
MatchOperation filterStates = Aggregation.match(cr);
Aggregation aggregation = newAggregation(filterStates, project("packageTypes")
.and(filter("packageTypes").as("item").by(valueOf("item.packageTypeId").equalToValue(1))
).as("packageTypes"));
AggregationResults<CommunityShopDOB> output = mongoTemplate.aggregate(aggregation, CommunityShopDOB.class,
CommunityShopDOB.class);
return output.getUniqueMappedResult();