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

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

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: &quot;$last_scraped&quot;}: 2017}},  {$group: {_id: {max: {$max: &quot;$price&quot;}}}} ])

the schema is:

{
last_scraped: &lt;String&gt;
price: &lt;int&gt;
}

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&lt;Document&gt; aggregate =
   collection.aggregate(Arrays.asList(Aggregates.match(
   Filters.eq(&quot;last_scraped&quot;, 2017)), Aggregates.group(&quot;_id&quot;,
   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

假设您的模式是:

 {
    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: &lt;String&gt; //dd-mm-yyyy
    price: &lt;int&gt;
    }

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

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:

确定