简体   繁体   中英

How to get Unique Data and Mapped with Field in MongoDB

I am new on Mongo and trying to group the model data and map model code to model year.

Sample Data:

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

Expected 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. while I am using this approach but getting duplicate data. https://mongoplayground.net/p/Je0bR6ki7kP

You are actually pretty close. The only thing that is incorrect is that you are doing $addToSet using the whole model object, which makes the de-duplication failed. You can try below code:

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

Here is the Mongo playground for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM