在使用MongoOperations Spring Java保存日期至mongodb时出现错误。

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

Error while saving date in mongodb using MongoOperations Spring Java

问题

我需要在MongoDB中保存带有日期的JSON对象,这里是示例JSON:

  1. {
  2. "modifiedon": {
  3. "$dateFromString": {
  4. "dateString": "2017-02-08T12:10:40.787"
  5. }
  6. },
  7. "modifiedby": "ramsha-GRM1 Ambreen",
  8. "id": 537
  9. }

我期望 'modifiedOn' 的值应该保存为:

  1. "modifiedon": ISODate("2017-02-08T12:10:40.78")

以下是使用Java将JSON插入MongoDB的代码示例:

  1. String json = {<JSONVALUE>};
  2. mongoOperations.insert(json, "risk");

但是MongoOperations在保存JSON时没有处理 $dateFromString,该值在MongoDB中格式化为日期。非常感谢您提供任何线索。

英文:

I need to save json object in mongodb having dates, here is sample json:

  1. {
  2. &quot;modifiedon&quot;: {
  3. &quot;$dateFromString&quot;: {
  4. &quot;dateString&quot;: &quot;2017-02-08T12:10:40.787&quot;
  5. }
  6. },
  7. &quot;modifiedby&quot;: &quot;ramsha-GRM1 Ambreen&quot;,
  8. &quot;id&quot;: 537
  9. }

I expect 'modifiedOn' value should save as

  1. &quot;modifiedon&quot;: ISODate(&quot;2017-02-08T12:10:40.78&quot;)

Here is a code to insert json into mongodb using java

  1. String json = {&lt;JSONVALUE&gt;};
  2. mongoOperations.insert(json,&quot;risk&quot;);

But MongoOperations save JSON without process $dateFromString which is a date formatted in MongoDB. Any leads are highly appreciated thanks

答案1

得分: 0

在尝试之后,上述问题已通过修改输入的 JSON 对象来解决:

  1. {
  2. "modifiedon": {
  3. "$date": "2020-09-30T11:32:58.000Z"
  4. },
  5. "modifiedby": "ramsha-GRM1 Ambreen",
  6. "id": 229
  7. }

而且它以日期对象的形式保存在 MongoDB 中,我可以针对日期进行查询。

英文:

after hit an trial above issue has been resolved by modifying input JSON object as

{
&quot;modifiedon&quot;: {
&quot;$date&quot;: &quot;2020-09-30T11:32:58.000Z&quot;
},
&quot;modifiedby&quot;: &quot;ramsha-GRM1 Ambreen&quot;,
&quot;id&quot;: 229
}

AND it is saved in MongoDB as date object and I am able to query against date

huangapple
  • 本文由 发表于 2020年9月30日 14:08:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64131788.html
匿名

发表评论

匿名网友

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

确定