【问题标题】:MongoDB filter, orderby, aggregate on the array field?MongoDB过滤,orderby,数组字段上的聚合?
【发布时间】:2020-01-26 20:45:08
【问题描述】:

这是我的文档格式

[
    {
        "name" : "test1",
        "other_name" : "TEST1_1",
        "values" : ["11", "12", "13", "14"]
    },
    {
        "name" : "test2",
        "other_name" : "TEST2_1",
        "values" : ["21", "22", "23", "24"]
    },
    {
        "name" : "test3",
        "other_name" : "TEST3_1",
        "values" : ["11", "32", "13", "14"]
    }
]

我想要的输出为:

["11", "12", "13", "14", "21", "22", "23", "24", "32"]

我应该也可以对它们进行过滤(仅过滤值数组)、orderby(仅按值数组排序)。

你能帮我解决这个问题吗?

我试过这个:

db.collection.distinct('values', { "values" : /32/ }).sort(); 但这是返回所有值,如 "11", "32", "13", "14" 我只想要特定值,你能帮忙吗?

【问题讨论】:

  • 您想要的 o/p 已合并来自所有三个文档的唯一值,您所说的“我只想要特定值”是什么意思??

标签: python mongodb mongodb-query aggregation-framework pymongo


【解决方案1】:

您需要使用 MongoDB aggregation operations 来获得所需的输出

我们使用$unwind 运算符将values 展平。我们对值进行排序。然后我们$group 将所有文档合并为单个文档并存储所有值(重复)。使用$reduce,我们生成具有唯一值的新数组。

注意:聚合返回对象数组

db.collection.aggregate([
  {
    $unwind: "$values"
  },
  {
    $sort: {
      values: 1
    }
  },
  {
    $group: {
      _id: null,
      values: {
        $push: "$values"
      }
    }
  },
  {
    $project: {
      _id: 0,
      values: {
        $reduce: {
          input: "$values",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              {
                $cond: [
                  {
                    $in: [
                      "$$this",
                      "$$value"
                    ]
                  },
                  [],
                  [
                    "$$this"
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  }
])

MongoPlayground

不清楚只有特定值

是什么意思

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2014-02-27
    • 2019-05-10
    • 2016-05-03
    相关资源
    最近更新 更多