草庐IT

java - 无法将聚合查询从 mongodb 转换为 Spring Data MongoDb

coder 2023-11-03 原文

我在尝试使用聚合对象将我在 mongodb 中的查询转换为 Spring Data MongoDb 时遇到了问题。我在 mongo 中有以下文档:

{
"_id" : ObjectId("596ce468798b61179c6442bb"),
"_class" : "com.test.model.User",
"name" : "Oi",
"surName" : "Alo",
"workLogs" : [
    {
        "_id" : ObjectId("596ce468798b61179c6442bc"),
        "day" : 1,
        "month" : 1,
        "year" : 2017,
        "timeEntrance" : "8:00",
        "lunchLeave" : "12:00",
        "lunchBack" : "13:00",
        "timeLeave" : "18:00"
    },
    {
        "_id" : ObjectId("596ce468798b61179c6442bd"),
        "day" : 2,
        "month" : 1,
        "year" : 2017,
        "timeEntrance" : "8:00",
        "lunchLeave" : "12:00",
        "lunchBack" : "13:00",
        "timeLeave" : "18:00"
    }
  ]
}

我想查询同一年同月的所有工作日志,然后我只想获取工作日志数组作为结果。我使用这个查询设法用 mongo 做到了:

db.user.aggregate([
  {$unwind: '$workLogs'}, 
  {$match: {'workLogs.month':2, 'workLogs.year':2017}}, 
  {$group: {_id:'$_id', workLogs:{$push: '$workLogs'}}}, 
  {$project: {'_id':0, 'workLogs': 1}}
]).pretty()

但我找不到如何将此查询转换为 Spring Data MongoDb,我想我快到了,如果有人能帮助我,我将不胜感激。这是我在 Java 中使用的代码。

Aggregation agg = Aggregation.newAggregation(
  unwind("workLogs"),
  match(Criteria
    .where("_id").is(userId)
    .and("workLogs.month").is(1)
    .and("workLogs.year").is(2017)
    ),
    group("_id"),
    group("horarios")
      .push(new BasicDBObject("workLogs", "workLogs")).as("workLogs"),
    project("workLogs")
);

AggregationResults<WorkLog> results = mongoTemplate.aggregate(agg, "workLogs", WorkLog.class);

提前谢谢大家!

最佳答案

不确定为什么你的 java 代码中有所有额外的字段。

shell查询的java等价代码是

 Aggregation agg = Aggregation.newAggregation(
   unwind("workLogs"),
   match(Criteria
      .where("workLogs.month").is(1)
      .and("workLogs.year").is(2017)
   ),
   group("_id").push("workLogs").as("workLogs"),
   project("workLogs").andExclude("_id")
 );

或者,您可以简化代码以使用 $filter

import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import static org.springframework.data.mongodb.core.aggregation.BooleanOperators.And.and;
import static org.springframework.data.mongodb.core.aggregation.ComparisonOperators.Eq;

 Aggregation agg = newAggregation(project().
     and(
      filter("workLogs").
      as("workLog").
      by(
       and(
          Eq.valueOf("workLog.month").equalToValue(1), 
          Eq.valueOf("workLog.year").equalToValue(2017)
      )
     )
    ).as("workLogs").
    andExclude("_id")
 );

关于java - 无法将聚合查询从 mongodb 转换为 Spring Data MongoDb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45438858/

有关java - 无法将聚合查询从 mongodb 转换为 Spring Data MongoDb的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  4. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  7. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  8. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  9. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  10. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

随机推荐