【问题标题】:MongoDB - find entries where field with specific name is present, nested anywhereMongoDB - 查找具有特定名称的字段存在的条目,嵌套在任何地方
【发布时间】:2021-01-13 02:00:16
【问题描述】:

我有一个 mongoDB 数据库,其中一些条目的字段名称为“rx”+该条目中另一个字段的值(我们称之为 rxid),因此该字段的最终名称可能类似于“rx1234”或“rx2836”。在此字段内有一个字典列表,其中可能包含名称为“A”和“B”的字段。我的任务是找出这个数据库中有多少条目至少有一个名为 A 或 B 的非空字段,无论它嵌套在哪里。我试图搜索嵌套查询,但是它总是需要指定“父”字段,在我的例子中是 rx 和其他字段的值的组合,所以它不是一个常量名称。

我的数据库架构类似于:

{ 
    "_id" : 1, 
    "rxid" 1234, 
    "rx1234" : [
        {
            "A" : "somevalue", 
            "B" : "someothervalue",  
        }, 
        {
            "A" : "somevalue2",
        }
    ]
},
{ 
    "_id" : 2, 
    "rxid" 2345
}

在这种情况下,我希望计算有多少对象的结构像 _id = 1 和多少像 _id = 2(里面可能还有其他字段,但它们无关紧要)

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    Refer this

    它检查rxCustomNumber 字段,然后检查该字段内的A/B。您可以简单地添加一个count 管道来获取计数。

    db.collection.aggregate([
      {
        "$project": {
          "concatValue": {//Form the dynamic field dynamically
            "$concat": [
              "rx",
              {
                "$toString": "$rxid"
              }
            ]
          },
          "data": {
            "$objectToArray": "$$ROOT"
          }
        }
      },
      {//Restructure the field
        $unwind: "$data"
      },
      {
        $match: {
          $and: [//Check for the match
            {
              $expr: {
                "$eq": [
                  "$concatValue",
                  "$data.k"
                ]
              }
            }
          ]
        }
      },
      {//Print the existence
        "$project": {
          "data.v.A": 1,
          "data.v.B": 1
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2015-09-20
      相关资源
      最近更新 更多