【问题标题】:Mongo - equivalence between distinct and aggregateMongo - 不同和聚合之间的等价
【发布时间】:2020-07-07 12:57:45
【问题描述】:

嗨:我在用聚合查询替换 mongo 独特的“本机”功能时遇到了一些问题。

在我的情况下,我的查询是这样的:

db.collection.distinct('stuff.shape')

mongo 然后返回一个具有不同 object.field 值的数组,例如

['square','triangle','circle']

但使用聚合

db.collection.aggregate([
{   $match:{ 'stuff.shape':{$exists: true} }  },
{   $group:{ '_id': '$stuff.shape'}   }
])

返回许多元素,如

{'_id':['triangle']}
{'_id':['square']}
{'_id':['circle']}

我的目标是获得与原生聚合相同的列表。

这是因为我要“区分”的表达式有一些计算数据我不能直接放入 distinct

样本数据:

[
  {
    "type": "obligation",
    "stuff": {
      "name": "must-turn-right",
      "shape": "circle"
    }
  },
  {
    "type": "information",
    "stuff": {
      "name": "town_name",
      "shape": "square"
    }
  },
  {
    "type": "obligation",
    "stuff": {
      "name": "yeld",
      "shape": "triangle"
    }
  },
  {
    "type": "danger",
    "stuff": {
      "name": "beware_of_cattle",
      "shape": "triangle"
    }
  }
]

link to mongoplaygroud

【问题讨论】:

  • Aggregate 返回一个对象数组,因此您无法获得像['square','triangle','circle'] 这样的字符串数组。但是,您可以获得的最接近的是一个对象数组,其中包含一个包含预期数组的字段,例如[{ _id: ['square','triangle','circle'] }]。您可以通过使用另一个 $group 来实现这一点

标签: mongodb aggregation-framework distinct


【解决方案1】:

正如@thammada.ts 已经说过的那样,不可能从aggregate 函数中获得与distinct 函数的输出等效的字符串数组。

通过在聚合管道中添加一个额外的$group 阶段,可以创建一个聚合查询,该查询返回一个文档,其中包含不同值作为文档中的一个数组:

db.collection.aggregate([
{   $match:{ 'stuff.shape':{$exists: true} }  },
{   $group:{ '_id': '$stuff.shape'}   },
{   $group:{ '_id': null, 'shape': {$push: '$_id'}}}
])

给出输出

[{
  "_id": null,
  "shape": [
    "square",
    "circle",
    "triangle"
  ]
}]

【讨论】:

    【解决方案2】:

    聚合管道返回文档。如果您想要一个字段值数组,则需要在您的应用程序中执行该转换。

    【讨论】:

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