如何使用带有arrayFilters的Filtered位数运算符来应用更新 [英] How to apply update using Filtered positional operator with arrayFilters

查看:90
本文介绍了如何使用带有arrayFilters的Filtered位数运算符来应用更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mongodb 3.6上运行,使用mongo驱动程序3.4.3和spring数据mongo 1.5.10。以下是我的文件结构

I am running on Mongodb 3.6, with mongo driver 3.4.3 and spring data mongo 1.5.10. Below is the structure of my document

{
  "_id": 12345,
  "_class": "com.example.ProductRates",
  "rates": [
    {
      "productId": NumberInt(1234),
      "rate": 100.0,
      "rateCardId": NumberInt(1),
      "month": NumberInt(201801)
    },
    {
      "productId": NumberInt(1234),
      "rate": 200.0,
      "rateCardId": NumberInt(1),
      "month": NumberInt(201802)
    },
    {
      "productId": NumberInt(1234),
      "rate": 400.0,
      "rateCardId": NumberInt(2),
      "month": NumberInt(201803)
    },
    {
      "productId": NumberInt(1235),
      "rate": 500.0,
      "rateCardId": NumberInt(1),
      "month": NumberInt(201801)
    },
    {
      "productId": NumberInt(1235),
      "rate": 234,
      "rateCardId": NumberInt(2),
      "month": NumberInt(201803)
    }
  ]
}

我正在尝试对数据进行批量更新,如下所示

am trying to do bulk update on the data as shown below

db.rates.update(
  { "_id" : 1234 },
  { $set: { "rates.$[item].rate": 200  } },
  { multi: true, 
   arrayFilters: [ { "item.rateCardId": {$in: [ 1, 2]} } ]
  }
)

现在尝试将此代码转换为java。下面是我能够为批量更新案例实现的代码。正如预期的那样,由于$ []的使用,以下查询正在更新所有文档。我试图找出如何使用位置数组更新运算符(如$ [one])应用数组过滤器。

Now and trying to convert this code to java. Below is the code i was able to achieve for a bulk update case. As expected the below query is updating all the document due to the usage of $[]. Am trying to figure out how to apply array filters here using positional array update operators (like $[one] ).

WriteResult wr = getMongoTemplate().updateMulti(
            new Query(where("rates.rateCardId").is(1234)),
            new Update().set("rates.$[].rate", 200),
            ProductRates.class);

此外,我找不到足够的教程或文档,建议如何在Java中应用所有复杂的mongo查询。请建议是否有任何好书或教程我可以参考。

Also I could not find enough tutorials or documentation that suggests how to apply all the complex mongo queries in Java. please suggest if there are any good books or tutorial i can refer to.

推荐答案

那应该是:

WriteResult wr = getMongoTemplate().updateMulti(
  new Query(where("rates.rateCardId").is(1234)),
  new Update().set("rates.$[item].rate", 200),
  new UpdateOptions()
    .arrayFilters(
      Arrays.asList( Filters.in("item.rateCardId",Arrays.asList(1,2)) )
    ), 
  ProductRates.class
);

您需要确保底层Java驱动程序是3.6.x或更高版本才能拥有 arrayFilters()甚至可能支持添加 UpdateOptions()

You need to make sure the underlying Java Driver is a 3.6.x version or greater in order to have the arrayFilters() and likely even to support the addition of UpdateOptions()

这篇关于如何使用带有arrayFilters的Filtered位数运算符来应用更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆