Search code examples
arraysmongodbmongodb-query

Find two objects with the same type in mongoDB


I have an arrays of objects as below in my data:

traits = [{type: 'Language' , val: 'English'} , {type: 'Age' , val: 37} , {type: 'Language' , val: 'Spanish'}]

I need to find out if each of the traits arrays I have in my documents, have at least two 'Language' types. if they do update the val to 'MultiLang'.

What is the best way to get this done?


Solution

  • I'm not sure what is your expected result, but if I understand you correctly, you can use update with pipeline:

    db.collection.update({},
    [
      {$set: {
          language: {$filter: {
              input: "$traits",
              cond: {$eq: ["$$this.type", "Language"]}
          }},
          traits: {$filter: {
              input: "$traits",
              cond: {$ne: ["$$this.type", "Language"]}
          }}
      }},
      {$set: {
          language: {
            type: "Language",
            val: {$cond: [
                {$gt: [{$size: "$language"}, 1]},
                "MultiLang",
                {$first: "$language.val"}
            ]}
          }
      }},
      {$set: {
          traits: {$concatArrays: [
              "$traits",
              [{$first: "$language"}]
          ]},
          language: "$$REMOVE"
      }}
    ])
    

    See how it works on the playground example