英文:
How can I query MongoDB that gives me the maximum price of an object in a user-decided year in a java application?
问题
以下是翻译好的内容:
我想使用以下查询:
db.listings_detail.aggregate([
{
$match: {
"last_scraped": { $year: "$last_scraped" }: 2017
}
},
{
$group: {
_id: { max: { $max: "$price" } }
}
}
])
架构如下:
{
last_scraped: <String>,
price: <int>
}
"Last scraped" 是以西班牙日期格式 dd/mm/yyyy,我不知道如何只获取年份。
在 Java 中,我有以下代码:
AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
Aggregates.match(Filters.eq("last_scraped", 2017)),
Aggregates.group("_id", Accumulators.max("max", "$price"))
));
我会用 MongoDB 进行查询测试,然后必须在 Java 中实现它。
英文:
I' want to use following query:
db.listings_detail.aggregate([ {$match: {{$year: "$last_scraped"}: 2017}}, {$group: {_id: {max: {$max: "$price"}}}} ])
the schema is:
{
last_scraped: <String>
price: <int>
}
Last scraped is in spanish format dd/mm/yyyy and i don't know how to get only the year
On java i have this code:
AggregateIterable<Document> aggregate =
collection.aggregate(Arrays.asList(Aggregates.match(
Filters.eq("last_scraped", 2017)), Aggregates.group("_id",
cumulators.max("max", "$price"))));
the tests of the queries I do with MongoDB and then I have to implement it in Java
答案1
得分: 0
假设您的模式是:
{
last_scraped: <String> //dd-mm-yyyy
price: <int>
}
您可以执行带有排序和选择第一个结果的查找查询
db.getCollection('listings_detail').find({"last_scraped": {"$regex": ".*2017$" }})
虽然推荐使用Mongo日期数据结构进行日期查询。以正则表达式结尾的查询属于COLLSCAN,随着数据大小的增长,性能表现将较差。
英文:
Assuming your schema is :
{
last_scraped: <String> //dd-mm-yyyy
price: <int>
}
You can do a find query with sort and select the first result
db.getCollection('listings_detail').find({"last_scraped": {"$regex": ".*2017$"} })
Although using mongo date data structure is recommened for date queries.
Ends with Regex is COLLSCAN, and will perform poorly as the data size grows.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论