简体   繁体   English

更新存储在yii2模型中的数组数组中的mongodb文档中的字段

[英]Update a field in mongodb document stored in a array of array in yii2 model

I have a database in mongodb for restaurants. 我在mongodb有一个餐馆数据库。 Sample database is as follows. 样本数据库如下。

{
   "restaurantId":"1",
   "menu":
   {
        "menuCategory":
        [
            {
                "menuCategoryId":"12"
                "menuItems":
                [
                    {
                        "menuId":"123",
                        "likesCount":0
                    },
                    {
                        "menuId":"1234",
                        "likesCount":0
                    }
                ]
            },
            {
                "menuCategoryId":"1290"
                "menuItems":
                [
                    {
                        "menuId":"2222",
                        "likesCount":0
                    },
                    {
                        "menuId":"3333",
                        "likesCount":0
                    }
                ]
            }
        ]
   }
}

In this document, I have to either increase or decrease the likes count against the menuId and restaurantId which is received in yii2. 在本文档中,我必须增加或减少yii2中收到的menuId和restaurantId的喜欢计数。 I am not able to find the likes count for the particular menuId in the restaurant to update it. 我无法找到喜欢计算在餐厅的特定menuId更新它。

I tried the following query to update the likesCount. 我尝试了以下查询来更新likesCount。

db.restaurants.update({$and:[{"restaurantId":"1"},{"menu.menuCategory.menu.menuId":"123"}]}, {$set:{"likesCount":5}})

This query may help you:- 此查询可能会帮助您: -

db.restaurants.update(
{$and:[{"restaurantId":"1"},
{"menu.menuCategory.menuItems.menuId":"123"}]}, 
{$set:{"menu.menuCategory.0.menuItems.0.likesCount":5}})

EDIT 编辑

Try something like below:- 尝试以下内容: -

 db.restaurants.find(
 {"restaurantId":"1","menu.menuCategory.menuItems.menuId":"123"}).toArray(
function(err, result)
{
    var index,found = false;
  for(var j in result[0].menu.menuCategory){
    for(var i in result[0].menu.menuCategory[j].menuItems)
    {
         if(results[0].menu.menuCategory[j].menuItems[i].menuId == "123")
         {
            found = true;
            index = i;
            break;
        }  
     }}

  if(found)
  {
       var x = 'menu.menuCategory.$.menuItems.'+index+'.likes';

       var  updateObject = {$set : {}};    
       updateObject['$set'][x] = 5;

      db.restaurants.update(
    {"restaurantId":"1",
   "menu.menuCategory.menuItems.menuId":"123"}, updateObject);
  }
});

See if this can help you. 看看这是否可以帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM