spring - MongoDB Spring - 动态获取值
问题描述
我在不同的集合中有以下文档
资产
{
"_id": "1234",
"name": "Needle",
"initialStock": 20
},
{
"_id": "12345",
"name": "Serum",
"initialStock": 5
}
储备金
{
"_id: "12345,
"from" : ISODate("2019-07-30T07:09:00.000Z"),
"to" : ISODate("2019-08-30T11:00:00.000Z"),
"assets": [
{
"_id": "1234",
"assignedStock": 10
},
"_id": "12345",
"assignedStock": 1
}
]
}
我怎样才能得到两个给定日期之间assignedStock
的减法?initialStock
例如“我想知道该资产在两个日期(从开始到结束)之间的可用库存”。
如何在 Spring 上做到这一点?(普通的 Mongo 也会给我一个线索)。
我当前的代码如下,但我只是在资产中得到一个空数组:
LookupOperation lookupOperation = LookupOperation.newLookup()
.from("assets")
.localField("assets._id")
.foreignField("_id")
.as("assets");
Criteria criteria = Criteria.where("from")
.gte(from)
.and("to")
.lte(to)
.and("assets")
.not().size(0)
.elemMatch(
Criteria.where("_id")
.is(idAsset)
);
Aggregation aggregation = Aggregation.newAggregation(match(criteria), lookupOperation);
List<Document> results =
this.mongoTemplate.aggregate(aggregation, "reserved", Document.class).getMappedResults();
解决方案
这很棘手,即使我是 MongoDB 新手,也觉得这个查询很有挑战性。但是,我设法编写了一个查询,该查询返回您所需的输出。我已经使用 mongo playgroud 来模拟您在问题中指定的场景。
db.reserves.aggregate([
{
$unwind: {
path: "$assets"
}
},
{
$group: {
_id: "$assets._id",
sumAssigned: {
$sum: "$assets.assignedStock"
},
}
},
{
$lookup: {
from: "assets",
localField: "_id",
foreignField: "_id",
as: "asset_lookup"
}
},
{
$project: {
sumAssigned: 1,
initialStock: {
$sum: "$asset_lookup.initialStock"
},
availableStock: {
$subtract: [
"$sumAssigned",
{
$sum: "$asset_lookup.initialStock"
}
]
}
}
}
])
https://mongoplayground.net/p/h5eMWIE5q4p // 新解决方案
https://mongoplayground.net/p/r1bcoUjD3eG // 旧解决方案
我使用了带有展开、查找和项目操作符的聚合管道。希望它可以帮助你。
推荐阅读
- java - Android Studio 网格布局无法正常工作
- c++ - 使用函数指针返回地址
- http - 如何向用户的浏览器传达它发出的 POST 请求没有副作用?
- laravel - Laravel 形式未定义
- database - 优化数据库设计以最大化数据冗余并增加信息的可访问性
- mysql - 如何将新条目添加到 mysql 表中,但仅适用于 1 列,同时保留所有其他列数据
- python-3.x - 变量在函数中运行时表示它为 False,但随后又恢复为 True
- python - 在 Python/R 中使用 SLINK 后分离集群
- netlogo - 如何确定我需要在 netlogo 中执行的运行次数以减少随机化的影响?
- r - 如何在 R 数据框中最容易地将多列放置为单列?