簡體   English   中英

如何在 MongoDB 中獲取唯一數據並與字段映射

[英]How to get Unique Data and Mapped with Field in MongoDB

我是 Mongo 的新手,並試圖將 model 數據和 map model 代碼分組到 Z20F35E630DAF44DB84C39 年。

Sample Data:

[
   {
      "model":[
         {
            "modelCode":"Z34L",
            "modelName":"370Z",
            "modelYear":"2009 - Present"
         }
      ]
   },
   {
      "model":[
         {
            "modelCode":"Z35L",
            "modelName":"370Z",
            "modelYear":"2010 - Present"
         }
      ]
   }
]

預期 Output:

[
   {
      "modelName":"370Z",
      "modelYear":{
         "Z34L":"2009 - Present",
         "Z35L":"2010 - Present"
      }
   }
]

in the above example, we group by model name and found 2 model years and put the model year key with key as model code and value as model year. 當我使用這種方法但得到重復數據時。 https://mongoplayground.net/p/Je0bR6ki7kP

你實際上很接近。 唯一不正確的是您正在使用整個model object 執行$addToSet ,這會導致重復數據刪除失敗。 你可以試試下面的代碼:

db.collection.aggregate([
  {
    "$unwind": "$model"
  },
  {
    "$group": {
      "_id": {
        "modelName": "$model.modelName"
      },
      "modelYearListing": {
        "$addToSet": {
          k: "$model.modelCode",
          v: "$model.modelYearListing"
        }
      }
    }
  },
  {
    "$project": {
      _id: 0,
      "modelName": "$_id.modelName",
      modelYear: {
        "$arrayToObject": "$modelYearListing"
      }
    }
  }
])

這是Mongo游樂場供您參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM