【问题标题】:How to select a value in mongodb aggregate query whose key name is in value如何在mongodb聚合查询中选择键名在值中的值
【发布时间】:2020-03-30 09:05:44
【问题描述】:

我有如下数据

 {
    "_id": "5de23837d7231325d0e3f9ad",
        "status": "cancelled",
        "createdAt": "2019-11-30T09:36:09.712Z",
        "user": "5d73677739be3a2340870dd2",
        "platform": "ios",
        "products": {
          "discount": 88,
          "_id": "5de23811014f0209345b54ef",
          "roomArrangement": [],
          "category": "adventure",
          "adventure": {
            "title": "This is high1",
            "location": {
              "code": "code",
              "name": "Manali",
              "state": {
                "code": "123",
                "name": "state",
                "slug": "state"
              }
         }
 }

现在我想选择一个值为类别的键。在上面的示例中 category = "adventrue" 然后选择冒险类别。意味着我需要选择 products.adventure 但冒险是我将从类别中获得的动态键。请教我怎么做

【问题讨论】:

    标签: node.js database mongodb aggregate


    【解决方案1】:

    试试这个:

    db.collection.aggregate([
       { $addFields: { product_data: { $objectToArray: "$products" } } },
       { $match: { $expr: { $in: ["$products.category", "$product_data.k"] } } },
       { $unset: "product_data" }
    ])    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多