从mongoDB中的嵌套对象设置字段属性

cgvd09ve  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(121)

我有一个如下格式的结构,我需要将新属性$User.Concerts.UserTitle的值设置为$User.Concerts.User.Title
我尝试过类似于“用户.音乐会.用户标题”的内容:“$User.Concerts.Users.Title”。这会将新属性设置为数组而不是字符串。如何修复?

{
    "Id": "Id1",
    "Title": "Title1",
    "User": [
        {
            "Id": "Userid2",
            "Title": "User Title1",
            "Concerts": [
                {
                    "Id": "Concert4",
                    "Title": "Concert title1",
                    "Users": {
                        "Id": "Userid2",
                        "Title": "User Title2 Concert4"
                    }
                },
                {
                    "Id": "Concert1",
                    "Title": "Concert title1",
                    "Users": {
                        "Id": "Userid2",
                        "Title": "User Title2 Concert1"
                    }
                }
            ]
        },
        {
            "Id": "Userid1",
            "Title": "User Title1",
            "Concerts": [
                {
                    "Id": "Concert1",
                    "Title": "Concert title1",
                    "Users": {
                        "Id": "Userid1",
                        "Title": "User Title Concert1"
                    }
                },
                {
                    "Id": "Concert2",
                    "Title": "Concert title1",
                    "Users": {
                        "Id": "Userid1",
                        "Title": "User Title Concert2"
                    }
                },
                {
                    "Id": "Concert3",
                    "Title": "Concert title1",
                    "Users": {
                        "Id": "Userid1",
                        "Title": "User Title Concert3"
                    }
                }
            ]
        }
    ]
}
r6hnlfcb

r6hnlfcb1#

试试这个:

db.collection.aggregate([
   {
      $set: {
         User: {
            $map: {
               input: "$User",
               as: "user",
               in: {
                  $mergeObjects: [
                     "$$user",
                     {
                        Concerts: {
                           $map: {
                              input: "$$user.Concerts",
                              as: "concert",
                              in: {
                                 $mergeObjects: [
                                    "$$concert",
                                    { UserTitle: "$$concert.Users.Title" }
                                 ]
                              }
                           }
                        }
                     }
                  ]
               }
            }
         }
      }
   }
])

Mongo Playground

相关问题