MongoDB-在集合中查找唯一的名称

时间:2019-10-30 18:38:11

标签: mongodb mapreduce aggregation-framework

假设我有这样的收藏

var sections: [PSSection] = [
  PSSection(..., models: [PSModel1(...), PSModel1(...), ]),
  PSSection(..., models: [PSModel2(...), PSModel2(...), ]),
  // ...
]

如何查找将MongoDB与Map-Reduce和Aggregation-Framework唯一名称一起使用? 结果应该是:John,Pedro,Mark

1 个答案:

答案 0 :(得分:2)

您可以使用$distinct(将返回所有唯一值)

db.collection.distinct("name")

[
    "Bob",
    "John",
    "Pedro",
    "Mark"
]

MongoDB聚合: $group,您可以在对值进行分组后进行过滤
(注意:汇总返回{key:value}对象的列表)

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      count: 1
    }
  },
  {
    $group: {
      _id: null,
      unique: {
        $push: "$_id"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

[
  {
    "unique": [
      "Pedro",
      "Mark",
      "John"
    ]
  }
]

MongoPlayground