【问题标题】:MongoDB: How to not repeat a collectionMongoDB:如何不重复收集
【发布时间】:2021-07-21 02:27:30
【问题描述】:

我的查询:

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}})

第二次尝试QUERY:

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

【问题讨论】:

    标签: mongodb collections aggregate distinct project


    【解决方案1】:

    你需要使用组,

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

    工作Mongo playground

    【讨论】:

    • 需要放“_id”吗?
    【解决方案2】:

    另一个解决方案是这个:

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

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2018-11-21
      • 2023-02-24
      相关资源
      最近更新 更多