Mongodb 3.6显示$ lookup中“ let”变量的空数据

时间:2019-07-18 12:56:27

标签: mongodb mongodb-3.6

我有收藏集

  

用户


  "userPreferences" : [ 
        {
            "categoryId" : "c8830898-7528-4d67-a3f2-b5d017ada693",
            "keywords" : [ 
                "fresh"
            ]
        }, 
        {
            "categoryId" : "874020e2-54f2-4cac-8b5b-17a60fd8350c"
        }, 
        {
            "categoryId" : "dc02c017-ec24-4d4c-8195-661e2fd863fb",
            "keywords" : [ 
                "red"
            ]
        }, 
        {
            "categoryId" : "9e2c2bc8-0006-4414-8d9b-3c1064ce47df"
        }
    ],
  

类别

{
    "_id" : ObjectId("5d27a73a2f8e7ee76a1f5943"),
    "id" : "2d3f0e96-bd8b-43c0-856d-1da434eb5bc8",
    "name" : "Dessert Sauces & Toppings",
    "parentId" : "ff7bb7c4-5e05-40c9-85cf-930fafc984bd"
}

{
    "_id" : ObjectId("5d27a73a2f8e7ee76a1f5944"),
    "id" : "b49296f7-4824-4d89-b86c-0e5cfe0e09cc",
    "name" : "Honey, Syrup & Nectar",
    "parentId" : "ff7bb7c4-5e05-40c9-85cf-930fafc984bd"
}

我想以

的格式获取数据

"userPreferences" : [ 
 { 
   id: "2d3f0e96-bd8b-43c0-856d-1da434eb5bc8", 
   name: 'Dessert Sauces & Toppings"', 
   keywords: ["test", "test2"]
 }
]

我使用mongoDB 3.6,所以我用$lookup查询从categories中找到匹配的类别项并返回它,但我也想从keywords中添加user集合。

db.getCollection('users').aggregate([
    {
       $lookup: {
          from: "categories",
          let: { "categoryId": "$userPreferences.categoryId", 
                 "keywords": "$userPreferences.keywords"},
          pipeline : [
                       { $match:{"$expr":{"$in"["$id","$$categoryId"]}}},
                       { $addFields: {"keywords": "$$keywords"`} }
                      ]
          as: "userPreferences"  
         }

     }

])

查找有效,但是keywords将始终为空

所以就像

"userPreferences" : [ 
   { id: "2d3f0e96-bd8b-43c0-856d-1da434eb5bc8,
     name: 'Honey, Syrup & Nectar'}
]

0 个答案:

没有答案