MongoDB - 在 collection 中查找唯一名称

MongoDB - Find unique names in collection

假设我有 collection 这样的

var list= [{name : "Bob", age : "22"},{name : "John", age : "21"}, {name : "Pedro", age : "15"}, {name : "Bob", age : "11"}, {name : "Mark", age : "24"}]

如何使用具有 map-reduce 和 aggregation-framework 唯一名称的 MongoDB 来查找? 结果应该是:John,Pedro,Mark

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

db.collection.distinct("name")

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

MongoDB 聚合: $group 您可以在分组值后进行过滤
(注意:聚合 returns {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