0

集合中的文档结构cities是这样的

城市

  {
   _id:  ObjectId("5e78ec62bb5b406776e92fac"),
   city_name: "Mumbai",
   ...
   ...
   subscriptions: [
    {
       _id: 1,
       category: "Print Magazine",
       subscribers: 183476
       options: [
         {
            name: "Time",
            subscribers: 56445
         },
         {
            name: "The Gentlewoman",
            subscribers: 9454
         },
         {
            name: "Gourmand",
            subscribers: 15564
         }
         ...
         ...
       ]
     },
     {
       _id: 2,
       category: "RSS Feed",
       subscribers: 2645873
       options: [
         {
            name: "Finance",
            subscribers: 168465
         },
         {
            name: "Politics",
            subscribers: 56945
         },
         {
            name: "Entrepreneurship",
            subscribers: 56945
         },
         ...
         ...
       ]
     }
   ]
}

现在当用户订阅如下

{
  cityId: 5e78ec62bb5b406776e92fac
  selections: [
    {
      categoryId: 1,
      options : ["Time", "Gourmand"]
    }, 
    {
      categoryId: 2, 
      selected: ["Politics", "Entrepreneurship"]
    }    
  ]
}

我想更新文档中的以下cities内容

  • 将“印刷杂志”的订阅者增加 1
    • 将“时间”的订阅者增加 1
    • 将“美食家”的订阅者增加 1
  • 将“RSS Feed”的订阅者增加 1
    • 将“政治”的订阅者增加 1
    • 将“创业”的订阅者增加 1

因此,当一个项目被订阅时,它的订阅者计数增加 1。它所属的类别,它的订阅者计数也增加 1。

我想在单个更新查询中实现这一点。任何提示我该怎么做?

用例详情

每个用户的订阅详细信息都存储在user_subscription_details集合中(此处未列出)。subscriptions属性 incities仅保存每个城市的订阅摘要。

4

1 回答 1

0

所以我可以通过以下查询

db.cities.updateOne(
{
   _id : ObjectId("5e78ec62bb5b406776e92fac")
},
{ 
   $inc: { 
     "subscriptions.$[category].subscribers" : 1,
     "subscriptions.$[category].options.$[option].subscribers" : 1
   }
},
{ multi: true,
   arrayFilters: [
     { "category._id": {$in: ["1", "2"]} },
     { "option.name": {$in: ["Time", "Gourmand", "Politics", "Entrepreneurship"]} } 
   ]
}
)

简要说明

  • 首先文档与_id.
  • 在更新块中,我们将声明要更新的字段
    • “订阅。$ [ ?]。订阅者”:1,
    • “订阅。$[ ?].options.$[ ?].subscribers”:1

我在?这里用来表明我们还不知道我们需要对数组中的哪些元素进行这些更新。我们可以通过过滤需要更新的数组元素在下一个块中声明它。

  • 在过滤器块中,我们在某些条件下过滤数组元素
    • { "category._id": {$in: ["1", "2"]} }
    • { "option.name": {$in: ["Time", "Gourmand", "Politics", "Entrepreneurship"]} }

首先,我们过滤外部数组中的元素,_id即仅订阅类别_id12。接下来,我们在字段上过滤内部options数组中的元素。name将通过两个过滤器的元素将得到更新。

注意:categoryincategory._idoptioninoption.name可以是任何名称。但更新块中的字段路径将使用相同的名称。

对于,Spring Boot MongoOperation 翻译这个查询看这个答案

于 2020-03-29T10:34:55.343 回答