MongoDB Spring 数据,具有复杂条件的最大聚合
MongoDB Spring data, max aggregate with complex condition
我正在使用 mongodb 作为面向文档的数据库,并使用 spring 数据作为 ODM。我正面临困难,对复杂的 bson 结构执行最大聚合。
我必须从所有文档中找到最大日期,但如果文档有嵌入文档,则必须考虑该嵌入文档的最大日期。
这是一个示例,假设我有一个名为 person 的集合,并且 person 集合包含以下文档。
{
"_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
"name" : "abc",
"birth_date_time" : '15 June 1988'
"children" : {
"_id" : ObjectId("55def1ceb2223ed74ddf2b5ce"),
"name" : "def",
"birth_date_time" : '10 April 2010'
}
},
{
"_id" : ObjectId("55def1ceb5b5ed74dd232323"),
"name" : "xyz",
"birth_date_time" : '15 June 1986'
},
{
"_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
"name" : "mno",
"birth_date_time" : '18 March 1982'
"children" : {
"_id" : ObjectId("534ef1ceb2223ed74ddf2b5ce"),
"name" : "pqr",
"birth_date_time" : '10 April 2009'
}
}
它应该是 return 2010 年 4 月 10 日,因为这是集合中某个人的最大出生日期。我想知道谁使用 spring 数据存储库来实现它。
这是 MongoDB 聚合。它们应该很容易在 Spring 数据中实现。
db.person.aggregate([
{$group: {
_id: null,
maxDate: {$max : {
$cond: [
{$gt : ["$birth_date_time","$children.birth_date_time"]},
"$birth_date_time",
"$children.birth_date_time"
]}}
}}
])
或使用 $project
:
db.person.aggregate([{
$project: {
mDate: {
$cond: [
{$gt : ["$birth_date_time","$children.birth_date_time"]},
"$birth_date_time",
"$children.birth_date_time"
]
}
}},
{$group: {
_id: null,
maxDate: {$max : "$mDate"}
}},
])
我正在使用 mongodb 作为面向文档的数据库,并使用 spring 数据作为 ODM。我正面临困难,对复杂的 bson 结构执行最大聚合。 我必须从所有文档中找到最大日期,但如果文档有嵌入文档,则必须考虑该嵌入文档的最大日期。 这是一个示例,假设我有一个名为 person 的集合,并且 person 集合包含以下文档。
{
"_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
"name" : "abc",
"birth_date_time" : '15 June 1988'
"children" : {
"_id" : ObjectId("55def1ceb2223ed74ddf2b5ce"),
"name" : "def",
"birth_date_time" : '10 April 2010'
}
},
{
"_id" : ObjectId("55def1ceb5b5ed74dd232323"),
"name" : "xyz",
"birth_date_time" : '15 June 1986'
},
{
"_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
"name" : "mno",
"birth_date_time" : '18 March 1982'
"children" : {
"_id" : ObjectId("534ef1ceb2223ed74ddf2b5ce"),
"name" : "pqr",
"birth_date_time" : '10 April 2009'
}
}
它应该是 return 2010 年 4 月 10 日,因为这是集合中某个人的最大出生日期。我想知道谁使用 spring 数据存储库来实现它。
这是 MongoDB 聚合。它们应该很容易在 Spring 数据中实现。
db.person.aggregate([
{$group: {
_id: null,
maxDate: {$max : {
$cond: [
{$gt : ["$birth_date_time","$children.birth_date_time"]},
"$birth_date_time",
"$children.birth_date_time"
]}}
}}
])
或使用 $project
:
db.person.aggregate([{
$project: {
mDate: {
$cond: [
{$gt : ["$birth_date_time","$children.birth_date_time"]},
"$birth_date_time",
"$children.birth_date_time"
]
}
}},
{$group: {
_id: null,
maxDate: {$max : "$mDate"}
}},
])