如何在Java应用程序中查询MongoDB,以获取用户指定年份内对象的最高价格?

huangapple go评论99阅读模式
英文:

How can I query MongoDB that gives me the maximum price of an object in a user-decided year in a java application?

问题

以下是翻译好的内容:

我想使用以下查询:

  1. db.listings_detail.aggregate([
  2. {
  3. $match: {
  4. "last_scraped": { $year: "$last_scraped" }: 2017
  5. }
  6. },
  7. {
  8. $group: {
  9. _id: { max: { $max: "$price" } }
  10. }
  11. }
  12. ])

架构如下:

  1. {
  2. last_scraped: <String>,
  3. price: <int>
  4. }

"Last scraped" 是以西班牙日期格式 dd/mm/yyyy,我不知道如何只获取年份。

在 Java 中,我有以下代码:

  1. AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
  2. Aggregates.match(Filters.eq("last_scraped", 2017)),
  3. Aggregates.group("_id", Accumulators.max("max", "$price"))
  4. ));

我会用 MongoDB 进行查询测试,然后必须在 Java 中实现它。

英文:

I' want to use following query:

  1. db.listings_detail.aggregate([ {$match: {{$year: &quot;$last_scraped&quot;}: 2017}}, {$group: {_id: {max: {$max: &quot;$price&quot;}}}} ])

the schema is:

  1. {
  2. last_scraped: &lt;String&gt;
  3. price: &lt;int&gt;
  4. }

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:

  1. AggregateIterable&lt;Document&gt; aggregate =
  2. collection.aggregate(Arrays.asList(Aggregates.match(
  3. Filters.eq(&quot;last_scraped&quot;, 2017)), Aggregates.group(&quot;_id&quot;,
  4. cumulators.max(&quot;max&quot;, &quot;$price&quot;))));

the tests of the queries I do with MongoDB and then I have to implement it in Java

答案1

得分: 0

假设您的模式是:

  1. {
  2. last_scraped: <String> //dd-mm-yyyy
  3. price: <int>
  4. }

您可以执行带有排序和选择第一个结果的查找查询

  1. db.getCollection('listings_detail').find({"last_scraped": {"$regex": ".*2017$" }})

虽然推荐使用Mongo日期数据结构进行日期查询。以正则表达式结尾的查询属于COLLSCAN,随着数据大小的增长,性能表现将较差。

英文:

Assuming your schema is :

  1. {
  2. last_scraped: &lt;String&gt; //dd-mm-yyyy
  3. price: &lt;int&gt;
  4. }

You can do a find query with sort and select the first result

  1. db.getCollection(&#39;listings_detail&#39;).find({&quot;last_scraped&quot;: {&quot;$regex&quot;: &quot;.*2017$&quot;} })

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.

huangapple
  • 本文由 发表于 2020年6月29日 01:42:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/62626157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定