MongoDB: 如何不重复一个集合

MongoDB: How to not repeat a collection

我的查询:

db.Customer.aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

结果:

{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 103, "CustName" : "Jose Nicholas" }
{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 101, "CustName" : "Maria Makiling" }

我的问题: 如您所见,我应该为 CustName 和 CustNum 设置 3 个名称。我的输出应该是这样的

{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 103, "CustName" : "Jose Nicholas" }
{ "CustNum" : 101, "CustName" : "Maria Makiling" }

如何实现? 我尝试使用 distinct 但它只显示错误。

第一次 尝试查询:

db.Customer.distinct().aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

第二次 尝试查询:

 db.Customer.distinct().aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

您需要使用群组,

db.collection.aggregate([
  {
    "$group": {
      "_id": "$CustName",
      "CustName": {
        "$first": "$CustName"
      },
      "CustNum": {
        "$first": "$CustNum"
      },
      
    }
  }
])

工作Mongo playground

另一个解决方案是这个:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      data: {
        $addToSet: {
          CustName: "$CustName",
          CustNum: "$CustNum"
        }
      }
    }
  },
  { $unwind: "$data" },
  { $replaceRoot: { newRoot: "$data" } }
])

Mongo Playground